package com.zj.osm.view.map.map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dinuscxj.progressbar.CircleProgressBar;
import com.flyco.dialog.widget.NormalDialog;
import com.google.android.gms.maps.model.LatLng;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.xw.repo.BubbleSeekBar;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.adapter.CementProductAdapter;
import com.zj.osm.entity.db.EquipmentDao;
import com.zj.osm.entity.db.LineDao;
import com.zj.osm.entity.db.PhotosDao;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.db.ProjectDao;
import com.zj.osm.entity.greendao.Equipment;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Photos;
import com.zj.osm.entity.greendao.Point;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.model.pojo.Equip;
import com.zj.osm.model.pojo.EquipModuleType;
import com.zj.osm.model.pojo.Module;
import com.zj.osm.model.pojo.ModuleType;
import com.zj.osm.utils.Configuration;
import com.zj.osm.utils.SQLiteDatabaseUtils;
import com.zj.osm.utils.view_utils.BoxBxChangeWindow;
import com.zj.osm.view.BaseActivity;
import com.zj.utils.data.LiveDataBus;
import com.zj.utils.view.dialog.CompassDialog;
import com.zj.utils.view.dialog.CompassInterface;
import com.zj.utils.view.image.ImageBean;
import com.zj.utils.view.image.ReleaseMsgAdapter;

import org.greenrobot.greendao.Property;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.annotations.NonNull;

import static com.zj.osm.App.getInstances;
import static com.zj.osm.utils.MyUtils.Distance;
import static com.zj.utils.utils.SpinnerUtils.setSpinnerItemSelectedByValue;
import static java.lang.Double.parseDouble;


/**
 * 修改项目的活动
 */
public class EquActivity extends BaseActivity implements View.OnClickListener, ReleaseMsgAdapter.OnDeleteItemListener, CompassInterface {
    private static final String TAG = "EquActivity";
    List<ModuleType> moduleTypesData = new ArrayList<>();
    private ReleaseMsgAdapter adapter;
    private Context context;
    private Long cid, id;
    private Point Point;
    private List<Photos> photosList = new ArrayList<>();
    private Spinner map_sp_dixing_sort;
    private Spinner map_sp_state;
    private EditText map_ed_note;
    private EditText map_ed_high;
    private LinearLayout linearLayout, layout;
    private List<Equipment> equipmentList = new ArrayList<>();
    private List<Equipment> getEquipmentList = new ArrayList<>();
    private ArrayList<Equip> equipList = new ArrayList<>();
    private List<ImageBean> imageBeanList = new ArrayList<>();
    private EditText map_ed_length;
    private EditText map_ed_width;
    private List<ImageBean> beanList = new ArrayList<>();
    private int equId;
    private TextView map_ed_name;
    private Set<ModuleType> mtAllSet = new HashSet<>();
    private String pointTitleString = "";
    List<String> adapter_dataq;
    private List<String> adapter_dataName = new ArrayList<>();
    private Spinner map_sp_type;
    private String currentPointbbh = "";
    private String flag;
    private String name = "杆塔";
    private String tLineId = "";
    private int zhuzhuang = 0;
    private boolean isFirst = true;
    private String shebeiName = "";
    private TextView equ_tv_names;
    private TextView equ_tv_name;
    private TextView equ_tv_xuan;
    private TextView equ_ed_levers;
    private TextView equ_ed_lever;
    private Spinner map_sp_equ;
    private CheckBox isFenzhigan, isSzFenzhigan;
    private String isFenzhiBoolea = "0";
    private LinearLayout fenzhiganLine;
    private Line intentLine;//传过来的当前线
    private TextView addLineSave;
    private Property ProjectId;
    private String mganguanGan = "";
    private EditText heighEt;
    private EditText heighChaEt;
    private BubbleSeekBar heightChaSeekBar;
    private CircleProgressBar circleBar;
    private BubbleSeekBar heighCircleBar;
    //高度
    private String heighEtValue = "0米";
    //高度差
    private String heighChaEtValue = "0米";
    private ImageView degreeIv;
    private RelativeLayout relatRt;
    //湖南道路名称
    private EditText mRoadName;
    private EditText map_ed_dljcc;
    private TextView srcMarkNameTv;
    private TextView srcMarkTv;
    private EditText gridNameEt;
    //湖南
    private Spinner equWellSpinner;
    //湖南道路位置
    private EditText RoadLocation;
    //资源状态
    private Spinner srcStateSpiner;
    //规划年
    private EditText ghYearEt;
    //电缆井地址
    private EditText equAdressEt;
    //道路性质是否隐藏[环网箱显示,电缆井隐藏]
    private LinearLayout RoadHidLt;
    //资源规格
    private LinearLayout reSpacerHindLt;
    //资源规格
    private EditText srcSpeEt;
    //道路性质
    private EditText RoadNatureEt;
    //电缆井尺寸、地址外层布局
    private LinearLayout llDljcc, llDljdz;
    /**
     * 根据值, 设置spinner默认选中:
     *
     * @param spinner 传入spinner控件
     * @param value   传入与之匹配的值
     */
    public static void setSpinnerProjectelectedByValue(Spinner spinner, @NonNull String value) {
        SpinnerAdapter apsAdapter = spinner.getAdapter(); //得到SpinnerAdapter对象
        if (apsAdapter != null) {
            int k = apsAdapter.getCount();
            for (int i = 0; i < k; i++) {
                if (value.trim().equals(apsAdapter.getItem(i).toString().trim())) {
                    spinner.setSelection(i, true);// 默认选中项
                    break;
                }
            }
        }
    }

    /**
     * 根据值, 设置spinner默认选中:
     *
     * @param spinner 传入spinner控件
     * @param value   传入与之匹配的值
     */
    public static void setSpinnerProjectelectedByUID(Spinner spinner, @NonNull String value) {
        SpinnerAdapter apsAdapter = spinner.getAdapter(); //得到SpinnerAdapter对象
        if (apsAdapter != null) {
            int k = apsAdapter.getCount();
            for (int i = 0; i < k; i++) {
                if (value.trim().equals(apsAdapter.getItem(i).toString().trim())) {
                    spinner.setSelection(i, true);// 默认选中项
                    break;
                }
            }
        }
    }

    Point ps;
    private Spinner zhuGanSpinner, fuGanSpinner;
    private LinearLayout dis_ll, zhufugan;
    private BubbleSeekBar heightSeekBar;
    private LinearLayout viewLine;
    private NestedScrollView nestedScrollView;
    private EditText progress_Et;
    private LinearLayout sheBaiLt;
    private LinearLayout yearHindLt;
    private TextView gotoProgramPage;

    @SuppressLint("NewApi")
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_equ);
        //region
        KeyboardUtils.fixAndroidBug5497(this);
        context = this;
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        Intent intent = getIntent();
        ps = intent.getParcelableExtra("point");
        intentLine = intent.getParcelableExtra("line");
        /*
          Log.e("intenLine=",intentLine.toString());
          Log.e("pointstosting", ps.toString());
        */
        //Point{id=6, name='杆塔', equipType_id=1, high='0.0', state='新建', pointId='3425aa8e-acd2-4d3d-9c78-d75490a18127', uid='daac48b0-4805-41bf-ac93-3d3806a12d01', DefaultLineType='1', mark='Z-6', equipType_name='直线杆', longitude=117.29050576686859, latitude=39.05071860442072, LegendTypeKey='TY_SNG', dangju=137.0, latA='null', latB='null', lonA='null', lonB='null', main_rod_uid='null', deputy_rod_uid='null', category='null', isT='', whether='0', batch='0', sblx='直线杆', glsb='Z-5', length='null', width='null', icon='ZXG', address='null', projectId=1, note='', equipmentList=[], multimediaList=[], lineList=[], daoSession=null, myDao=null}
        flag = intent.getStringExtra("flag");
        name = intent.getStringExtra("name");
        tLineId = intent.getStringExtra("tLineId");
        currentPointbbh = ps.getEquipType_name();
        cid = ps.getId();
        id = ps.getProjectId();
        isFenzhigan = findViewById(R.id.isTFenzhigan);
        nestedScrollView = findViewById(R.id.nestedScrollView);
        isSzFenzhigan = findViewById(R.id.isSzFenzhigan);
        //<!--zhuGanSpinner   fuGanSpinner-->
        zhuGanSpinner = findViewById(R.id.zhuGanSpinner);
        fuGanSpinner = findViewById(R.id.fuGanSpinner);
        fenzhiganLine = findViewById(R.id.fenzhiganLine);
        sheBaiLt = findViewById(R.id.sheBaiLt);
        zhufugan = findViewById(R.id.zhufugan);
        heightSeekBar = findViewById(R.id.height_bubbleSeekBar);
        heightChaSeekBar = findViewById(R.id.height_cha_bubbleSeekBar);
        heighEt = findViewById(R.id.heigh_et);
        heighChaEt = findViewById(R.id.heigh_cha);
        progress_Et = findViewById(R.id.progress_Et);
        heighCircleBar = findViewById(R.id.height_circle);
        viewLine = findViewById(R.id.viewLine);
        circleBar = findViewById(R.id.circleBar);
        degreeIv = findViewById(R.id.degreeIv);
        map_sp_type = findViewById(R.id.map_sp_type);
        //endregion
        //region湖南
        mRoadName = findViewById(R.id.RoadName);
        map_ed_dljcc=findViewById(R.id.map_ed_dljcc);
        RoadHidLt = findViewById(R.id.RoadHidLt);
        reSpacerHindLt=findViewById(R.id.reSpacerHindLt);
        srcSpeEt=findViewById(R.id.srcSpeEt);
        RoadNatureEt=findViewById(R.id.RoadNatureEt);
        srcMarkNameTv = findViewById(R.id.srcMarkNameTv);
        srcMarkTv = findViewById(R.id.srcMarkTv);
        gridNameEt=findViewById(R.id.gridNameEt);
        equWellSpinner = findViewById(R.id.equWell);
        RoadLocation = findViewById(R.id.RoadLocation);
        srcStateSpiner = findViewById(R.id.srcStateSp);
        ghYearEt = findViewById(R.id.ghYear);
        equAdressEt = findViewById(R.id.equAdress);
        yearHindLt = findViewById(R.id.yearHindLt);
        gotoProgramPage = findViewById(R.id.gotoProgramPage);
        llDljcc = findViewById(R.id.ll_dljcc);
        llDljdz = findViewById(R.id.ll_dljdz);
        //endregion
        //region
        if (ps.getLineDirection() != null && !ps.getLineDirection().isEmpty()) {
            progress_Et.setText(ps.getLineDirection());
        }
        degreeIv.setOnClickListener(v -> {
            Dialog mDialog = new CompassDialog(EquActivity.this);
            mDialog.show();
        });
        circleBar.setMax(360);
        heighEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                heighEtValue = s.toString().replace("米", "");
                if (!heighEtValue.startsWith(".") && heighEtValue.length() > 0) {
                    if (Float.parseFloat(heighEtValue) <= 10) {
                        heightSeekBar.setProgress(Float.parseFloat(heighEtValue));

                    } else {
                        heightSeekBar.setProgress(10);

                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        heighChaEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                heighChaEtValue = s.toString().replace("米", "");
                if (!heighChaEtValue.startsWith(".") && heighChaEtValue.length() > 0) {
                    if (Float.parseFloat(heighChaEtValue) <= 10) {
                        heightChaSeekBar.setProgress(Float.parseFloat(heighChaEtValue));
                    } else {
                        heightChaSeekBar.setProgress(10);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        /*progress_Et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s != null && !s.toString().isEmpty() && !s.toString().startsWith("-") && !s.toString().startsWith(".") && !s.toString().startsWith("+") && Float.parseFloat(s.toString()) >= -180 && Float.parseFloat(s.toString()) <= 180) {
                    heighCircleBar.setProgress(Float.parseFloat(s.toString()));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });*/
        nestedScrollView.setOnScrollChangeListener((View.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            heighCircleBar.correctOffsetWhenContainerOnScrolling();
            heightChaSeekBar.correctOffsetWhenContainerOnScrolling();
            heightSeekBar.correctOffsetWhenContainerOnScrolling();
        });
        circleBar.setProgressFormatter((progress, max) -> progress + "度");

        heighCircleBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {

            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
                progress_Et.setText(progressFloat + "");
                //-180度---180度范围    circle：设置380
                circleBar.setProgress(progress);
            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {

            }
        });
        heightChaSeekBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {

            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
                heighChaEtValue = progressFloat + "米";
                heighChaEt.setText(progressFloat + "米");
            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {

            }
        });
        heightSeekBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                Log.e("progress11=", progress + "");
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
                Log.e("progress22=", progress + "");
                heighEtValue = progressFloat + "米";
                heighEt.setText(progressFloat + "米");

            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                Log.e("progress33=", progress + "");
            }
        });
        //高度
        if (ps.getEqupmentHeight() != null) {
            heighEtValue = ps.getEqupmentHeight();
            heighEt.setText(ps.getEqupmentHeight());
            heightChaSeekBar.correctOffsetWhenContainerOnScrolling();
            heightSeekBar.setProgress(Float.parseFloat(ps.getEqupmentHeight().replace("米", "")));
            heightChaSeekBar.setProgress(Float.parseFloat(ps.getDipOfhorizon().replace("米", "")));

        }
        //高度差
        if (ps.getDipOfhorizon() != null) {
            heighChaEtValue = ps.getDipOfhorizon();
            heighChaEt.setText(ps.getDipOfhorizon());
        }
        if (ps.getIsT() != null) {
            isFenzhiBoolea = ps.getIsT();
            if (ps.getIsT().equals("1")) {//T分接
                isFenzhigan.setChecked(true);
            }
            if (ps.getIsT().equals("2")) {//十字接
                isSzFenzhigan.setChecked(true);
            }
        } else {
            isFenzhigan.setChecked(false);
            isSzFenzhigan.setChecked(false);

        }
        Point pointTitle = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Id.eq(cid)).build().list().get(0);
        TextView activity_tv_title = findViewById(R.id.activity_tv_title);
        LinearLayout zhuchangShebai = findViewById(R.id.zhuchangShebai);
        if (ps.getWhether() != null && (ps.getWhether().equals("3") || ps.getName().equals("地形点"))) {
            zhuchangShebai.setVisibility(View.GONE);

        }
        if (ps.getName().equals("地形点")) {
            sheBaiLt.setVisibility(View.VISIBLE);
            viewLine.setVisibility(View.VISIBLE);
        }
        LinearLayout equ_rl_fs = findViewById(R.id.equ_rl_fs);
        activity_tv_title.setText(pointTitle.getEquipType_name());
        pointTitleString = pointTitle.getName();
        dis_ll = findViewById(R.id.dis_ll);
        if (pointTitle.getName().trim().equals("设备")) {
            pointTitleString = "设备";
            equ_rl_fs.setVisibility(View.GONE);
            sheBaiLt.setVisibility(View.VISIBLE);
            if (pointTitle.getSblx().equals("电缆井")) {
                map_sp_type.setEnabled(false);
            }
        }
        fenzhiganLine = findViewById(R.id.fenzhiganLine);
        if (pointTitle.getName().equals("杆塔")) {
            map_sp_type.setEnabled(false);
            fenzhiganLine.setVisibility(View.VISIBLE);
            if (intentLine != null) {
                dis_ll.setVisibility(View.VISIBLE);

            }
        }
        buiLuNameber = findViewById(R.id.huiLuNumber);
        map_sp_type.setEnabled(false);
        initData();
        initView();
        //endregion
    }

    //湖南初始化数据
    private void initHuNan() {
        //环网箱
        //1.道路名称 ok
        //2.道路性质 no et
        //3.道路位置 ok
        //4.资源编号 ok
        //5.资源性质 no
        //6.资源规格 no
        //7.资源状态 ok
        assert Point != null;
        if (Point.getEquipType_name().equals("环网箱")) {
            srcMarkNameTv.setText("资源编号");
            RoadHidLt.setVisibility(View.VISIBLE);
            reSpacerHindLt.setVisibility(View.VISIBLE);
            srcMarkTv.setText("资源性质");
            llDljcc.setVisibility(View.GONE);
            llDljdz.setVisibility(View.GONE);
        }
        if (Point.getRoadName() != null) {
            mRoadName.setText(Point.getRoadName());
        }
        if (Point.getDljCC() != null){
            map_ed_dljcc.setText(Point.getDljCC());
        }
        if (Point.getRoadNature()!=null){
            RoadNatureEt.setText(Point.getRoadNature());
        }
        if (Point.getGridName()!=null){
            gridNameEt.setText(Point.getGridName());
        }
        if (Point.getReSpecfs()!=null){
            srcSpeEt.setText(Point.getReSpecfs());
        }

        String[] arrayList;
        //性质和资源性质
        if (Point.getEquipType_name().equals("电缆井")) {
            arrayList = getResources().getStringArray(R.array.calWeAtribut);

        } else {//环网箱
            arrayList = getResources().getStringArray(R.array.srcArraySp);
        }
        //适配器
        ArrayAdapter<String> srcArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayList);
        //设置样式
        srcArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        equWellSpinner.setAdapter(srcArrayAdapter);
        for (int selecteIndex = 0; selecteIndex < arrayList.length; selecteIndex++) {
            if (Point.getCabwellPy() == null) {
                equWellSpinner.setSelection(0);
                break;
            }
            if (Point.getCabwellPy() != null && Point.getCabwellPy().equals(arrayList[selecteIndex])) {
                equWellSpinner.setSelection(selecteIndex);
                break;
            }

        }


        if (Point.getRoadAdress() != null) RoadLocation.setText(Point.getRoadAdress());
        else {
            if (Point.getAddress() != null) {
                RoadLocation.setText(Point.getAddress());
            }
        }
        String[] arrayListRs = getResources().getStringArray(R.array.srState);
        for (int selecteIndex = 0; selecteIndex < arrayListRs.length; selecteIndex++) {
            if (Point.getRsState() == null) {
                srcStateSpiner.setSelection(0);
                break;
            }
            if (arrayListRs[selecteIndex].equals(Point.getRsState())) {
                srcStateSpiner.setSelection(selecteIndex);
                break;
            }
        }
        srcStateSpiner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (arrayListRs[position].equals("规划态")) {
                    yearHindLt.setVisibility(View.VISIBLE);
                } else {
                    yearHindLt.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        if (Point.getGhYear() != null) {
            ghYearEt.setText(Point.getGhYear());
        }
        if (Point.getAddress() != null) {
            equAdressEt.setText(Point.getAddress());
        }
        gotoProgramPage.setOnClickListener(this);





    }

    /**
     * 初始化数据
     */
    private void initData() {
        if (cid != 0) {
            try {
                Point = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Id.eq(cid)).build().list().get(0);
                photosList = App.getInstances().getDaoSession().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(cid)).build().list();
                equipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                getEquipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Qubie.eq(2)).build().list();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取设备信息
     *
     * @param str 设备ID
     * @return 设备信息
     */
    public List<Equip> getModules(int str) {
        List<Equip> strings = new ArrayList<>();
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType where component=" + str, null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            Equip equip = new Equip();
            equip.setId(cursor.getInt(0));
            equip.setName(cursor.getString(1));
            equip.setCode(cursor.getString(4));
            strings.add(equip);
        }
        cursor.close();

        return strings;
    }

    TextView buiLuNameber;
    EditText map_tv_locations;
    TextView map_tv_locationss;

    /**
     * 初始化界面
     */
    @SuppressLint("SetTextI18n")
    private void initView() {
        shebeiName = currentPointbbh;
        initRecyclerView();
        addLinearLayout();
        setLineXuanxing();
        getZFganView();
        initHuNan();
        /**
         * 等分模式
         * 开启
         */
        setDistanceView();
        EditText map_ed_address = findViewById(R.id.map_ed_address);
        LinearLayout map_ll_address = findViewById(R.id.map_ll_address);
        map_ed_length = findViewById(R.id.map_ed_length);
        map_ed_width = findViewById(R.id.map_ed_width);
        LinearLayout equ_rl_fs = findViewById(R.id.equ_rl_fs);
        if (Point != null && Point.getWhether() != null && Point.getEquipType_name() != null && (Point.getWhether().equals("3") || Point.getEquipType_name().equals("电缆拐点") || Point.getEquipType_name().equals("连接点"))) {
            equ_rl_fs.setVisibility(View.GONE);
        }
        LinearLayout equ_ll_dmt = findViewById(R.id.equ_ll_dmt);
        LinearLayout map_ll = findViewById(R.id.map_ll);
        LinearLayout map_ll_gl = findViewById(R.id.map_ll_gl);
        isFenzhigan.setOnCheckedChangeListener((buttonView, isChecked) -> {
            isSzFenzhigan.setChecked(false);
            if (isChecked) {
                isFenzhigan.setChecked(true);
                isFenzhiBoolea = "1";
            } else {
                isFenzhigan.setChecked(false);
                isFenzhiBoolea = "2";

            }

        });
        isSzFenzhigan.setOnCheckedChangeListener((buttonView, isChecked) -> {
            isFenzhigan.setChecked(false);
            if (isChecked) {
                isSzFenzhigan.setChecked(true);
                isFenzhiBoolea = "2";
            } else {
                isSzFenzhigan.setChecked(false);
                isFenzhiBoolea = "1";

            }
        });
        TextView equ_btn_equ = findViewById(R.id.equ_btn_equ);
        equ_btn_equ.setOnClickListener(this);
        ImageButton activity_ib_back = findViewById(R.id.activity_ib_back);
        activity_ib_back.setOnClickListener(this);
        TextView activity_tv_save = findViewById(R.id.activity_tv_save);
        activity_tv_save.setOnClickListener(this);
        activity_tv_save.setText(getString(R.string.map_quxiao));
        TextView equ_btn_add = findViewById(R.id.equ_btn_add);
        equ_btn_add.setOnClickListener(this);
        findViewById(R.id.boxChangeJl).setOnClickListener(this);
        TextView map_sp_sort = findViewById(R.id.map_sp_sort);
        ///TODO 2019年10月21日。修改部分。---------
        ///TODO 2019年10月21日。修改部分。---------
        TextView map_tv_dixing_sort = findViewById(R.id.map_tv_dixing_sort);
        map_sp_dixing_sort = findViewById(R.id.map_sp_dixing_sort);
        map_ed_name = findViewById(R.id.map_ed_name);
        map_sp_state = findViewById(R.id.map_sp_state);
        map_tv_locations = findViewById(R.id.map_tv_locations);//经度 时
        map_tv_locationss = findViewById(R.id.map_tv_locationss);//纬度 时
        map_ed_note = findViewById(R.id.map_ed_note);
        map_ed_note.setText(Point.getNote());
        map_sp_equ = findViewById(R.id.map_sp_equ);
        equ_fsss_rv = findViewById(R.id.equ_fsss_rv);
        RelativeLayout map_ll_dixing_sort = findViewById(R.id.map_ll_dixing_sort);
        try {
            if (Point.getEquipType_name().equals("环网箱")){
                map_ed_name.setText(null);
            }else {
                map_ed_name.setText(Point.getMark());
            }
            assert Point != null;
            map_tv_locations.setText(Point.getLongitude() + "");
            map_tv_locationss.setText(Point.getLatitude() + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        switch (Point.getName()) {
            case "地形点": {
                map_ll_gl.setVisibility(View.GONE);
                map_ll_address.setVisibility(View.VISIBLE);
                equ_rl_fs.setVisibility(View.GONE);
                equ_ll_dmt.setVisibility(View.GONE);
                equ_btn_equ.setVisibility(View.GONE);
                map_ll.setVisibility(View.VISIBLE);
                map_ed_address.setText(Point.getAddress());
                map_ed_length.setText(Point.getLength());
                map_ed_width.setText(Point.getWidth());
                map_tv_dixing_sort.setVisibility(View.VISIBLE);
                map_ll_dixing_sort.setVisibility(View.VISIBLE);
                final List<Equip> dixingList = getModules(4);
                map_sp_sort.setText("地形点");
                adapter_dataq = new ArrayList<>();
                for (int i = 0; i < dixingList.size(); i++) {
                    adapter_dataq.add(dixingList.get(i).getName());
                    equipList.add(dixingList.get(i));
                }
                adapter_dataName.addAll(adapter_dataq);
                List<Point> PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(id)).build().list();
                //适配器
                ArrayAdapter<String> arr_adapterq = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_dataq);
                //设置样式
                arr_adapterq.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                /**
                 * 关联
                 */
                //设置样式
                map_sp_equ.setAdapter(arr_adapterq);
                String glsb = "";
                if (PointList.size() > 0) {
                    if (!PointList.get(PointList.size() - 1).getName().equals("通讯线")) {
                        if (PointList.size() > 1) {
                            glsb = PointList.get(PointList.size() - 2).getMark();
                        } else {
                            glsb = "";

                        }
                    } else {
                        glsb = "";
                    }
                }
                //根据值, 设置spinner默认选中:
                if (glsb != null)
                    setSpinnerProjectelectedByValue(map_sp_equ, glsb);

                ///TODO 2019年10月21日。修改部分。---------
                final Equip[] ep = new Equip[1];
                final List<Equip> equip = getEquIp(4);


                map_sp_sort.setText("杆塔");
                //适配器
                ArrayAdapter<Equip> arr_adapter_ganta = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, equip);
                //设置样式
                arr_adapter_ganta.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_sp_type.setAdapter(arr_adapter_ganta);
                ///TODO 2019年10月21日。修改的需求直接跳转。默认没有下面一行。
                for (int i = 0; i < equip.size(); i++) {
                    if (currentPointbbh != null && equip.get(i).getName().trim().equals(currentPointbbh.trim())) {
                        setSpinnerProjectelectedByValue(map_sp_type, currentPointbbh);

                    }
                }
                map_sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        ep[0] = (Equip) map_sp_type.getSelectedItem();
                        Log.e(TAG, "onItemSelected: " + ep[0].toString1());//TX,DX,GL,HL,JZ,TL
                        if (ep[0].getCode().equals("TX") || ep[0].getCode().equals("DX") || ep[0].getCode().equals("GL") || ep[0].getCode().equals("HL") || ep[0].getCode().equals("JZ") || ep[0].getCode().equals("TL")) {
                            viewLine.setVisibility(View.VISIBLE);
                        } else {
                            viewLine.setVisibility(View.GONE);
                        }
                        if (PointList.size() > 0) {
                            map_ed_name.setText(ep[0].getCode() + "-" + (PointList.size()));

                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }
            break;
            case "杆塔": {
                final List<Equip> gantaList = getModules(1);
                map_sp_sort.setText("杆塔");


                List<String> adapter_data1 = new ArrayList<>();
                for (int i = 0; i < gantaList.size(); i++) {
                    adapter_data1.add(gantaList.get(i).getName());
                    equipList.add(gantaList.get(i));
                }
                adapter_dataName.addAll(adapter_data1);
                //适配器
                ArrayAdapter<String> arr_adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data1);
                //设置样式
                arr_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


                List<Point> PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(id)).build().list();
                List<String> adapter_data = new ArrayList<>();
                for (int i = 0, len = PointList.size() - 1; i < len; i++) {
                    if (PointList.get(i).getMark() != null && !PointList.get(i).getMark().equals("")) {
                        adapter_data.add(PointList.get(i).getMark());
                    } else {
                        adapter_data.add("未命名");
                    }
                }
                //适配器
                ArrayAdapter<String> arr_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data);

                /**
                 * 关联
                 */
                //设置样式
                arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_sp_equ.setAdapter(arr_adapter);
                String glsb = "";
                if (PointList.size() > 0) {
                    if (!PointList.get(PointList.size() - 1).getName().equals("通讯线")) {
                        if (PointList.size() > 1) {
                            glsb = PointList.get(PointList.size() - 2).getMark();
                        } else {
                            glsb = "";

                        }

                    } else {
                        glsb = "";
                    }
                }
                //根据值, 设置spinner默认选中:
                if (glsb != null)
                    setSpinnerProjectelectedByValue(map_sp_equ, glsb);


                ///TODO 2019年10月21日。修改部分。---------
                final Equip[] ep = new Equip[1];
                final List<Equip> equip = getEquIp(1);


                map_sp_sort.setText("杆塔");
                //适配器
                ArrayAdapter<Equip> arr_adapter_ganta = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, equip);
                //设置样式
                arr_adapter_ganta.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_sp_type.setAdapter(arr_adapter_ganta);
                ///TODO 2019年10月21日。修改的需求直接跳转。默认没有下面一行。
                for (int i = 0; i < equip.size(); i++) {
                    if (equip.get(i).getName().trim().equals(currentPointbbh.trim())) {
                        setSpinnerProjectelectedByValue(map_sp_type, currentPointbbh);
                    }
                }
                map_sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        ep[0] = (Equip) map_sp_type.getSelectedItem();
                        if (PointList.size() > 0) {
                            map_ed_name.setText(ep[0].getCode() + "-" + (PointList.size()));
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });


                map_sp_equ.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if (map_sp_equ.getSelectedItem() != null) {
                            String a = map_sp_equ.getSelectedItem().toString();
                            String regEx = "[0-9]+(?=[^0-9]*$)";
                            Pattern p = Pattern.compile(regEx);
                            Matcher m = p.matcher(a);
                            String replaceString = "";
                            while (m.find()) {
                                replaceString = m.group(0);

                            }
                            Equip epInsert = (Equip) map_sp_type.getSelectedItem();
                            map_ed_name.setText(epInsert.getCode() + replaceString);
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }
            break;
            default:
                final List<Equip> shebeiList = getModules(2);
                map_sp_sort.setText("设备");
                List<String> adapter_data3 = new ArrayList<>();
                for (int i = 0; i < shebeiList.size(); i++) {
                    adapter_data3.add(shebeiList.get(i).getName());
                    equipList.add(shebeiList.get(i));
                }
                adapter_dataName.addAll(adapter_data3);
                //适配器
                ArrayAdapter<String> arr_adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data3);
                //设置样式
                arr_adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


                List<Point> PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(id)).build().list();
                List<String> adapter_data = new ArrayList<>();
                for (int i = 0, len = PointList.size() - 1; i < len; i++) {
                    if (PointList.get(i).getMark() != null && !PointList.get(i).getMark().equals("")) {
                        adapter_data.add(PointList.get(i).getMark());
                    } else {
                        adapter_data.add("未命名");
                    }
                }
                //适配器
                ArrayAdapter<String> arr_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data);

                /**
                 * 关联
                 */
                //设置样式
                arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_sp_equ.setAdapter(arr_adapter);
                String glsb = "";

                if (PointList.size() > 0) {
                    if (!PointList.get(PointList.size() - 1).getName().equals("通讯线")) {

                        if (PointList.size() > 1) {
                            glsb = PointList.get(PointList.size() - 2).getMark();
                        } else {
                            glsb = "";

                        }

                    } else {
                        glsb = "";
                    }
                }
                //根据值, 设置spinner默认选中:
                if (glsb != null)
                    setSpinnerProjectelectedByValue(map_sp_equ, glsb);
                map_sp_equ.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if (map_sp_equ.getSelectedItem() != null) {
                            String a = map_sp_equ.getSelectedItem().toString();
                            String regEx = "[0-9]+(?=[^0-9]*$)";
                            Pattern p = Pattern.compile(regEx);
                            Matcher m = p.matcher(a);
                            String replaceString = "";
                            while (m.find()) {
                                replaceString = m.group(0);

                            }
                            Equip epInsert = (Equip) map_sp_type.getSelectedItem();
                            map_ed_name.setText(epInsert.getCode() + replaceString);
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });


                final Equip[] ep = new Equip[1];
                final List<Equip> equip2 = getEquIp(2);
                ///TODO 2019年10月21日。修改的需求直接跳转。默认没有下面一行。
                map_sp_sort.setText("设备");
                ep[0] = equip2.get(0);

                //适配器
                ArrayAdapter<Equip> arr_adapter_shebei = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, equip2);
                //设置样式
                arr_adapter_shebei.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_sp_type.setAdapter(arr_adapter_shebei);
                for (int i = 0; i < equip2.size(); i++) {
                    if (equip2.get(i).getName().trim().equals(currentPointbbh.trim())) {
                        setSpinnerProjectelectedByValue(map_sp_type, currentPointbbh);
                        if (currentPointbbh.equals("柱上变压器")) {
                            zhufugan.setVisibility(View.VISIBLE);

                        }
                    }
                }
                map_sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        ep[0] = (Equip) map_sp_type.getSelectedItem();
                        if (ep[0].getName().equals("柱上变压器")) {
                            zhufugan.setVisibility(View.VISIBLE);
                            lineLuMokuai.setVisibility(View.GONE);

                        } else {
                            zhufugan.setVisibility(View.GONE);
                            lineLuMokuai.setVisibility(View.VISIBLE);


                        }
                        if (!PointList.isEmpty()) {
                            map_ed_name.setText(ep[0].getCode() + "-" + (PointList.size()));
                            /**
                             * 为了跟新设备点模块添加下啦内容。
                             * */
                            Equip PointEquip = (Equip) map_sp_type.getSelectedItem();
                            Point.setDefaultLineType(PointEquip.getDefaultLineType());
                            shebeiName = PointEquip.getName();
                            if (equ_tv_names != null) {
                                equ_tv_names.setText(shebeiName);
                                equ_ed_levers.setText("设置值");

                            }
                            if (equ_tv_xuan != null) {
                                equ_tv_xuan.setText("设置值");
                            }
                            if (equ_tv_name != null) {
                                equ_tv_name.setText(shebeiName);
                                equ_ed_lever.setText("设置值");
                            }
                            equId = PointEquip.getId();
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
                break;
        }

        Button map_btn_cancel = findViewById(R.id.map_btn_cancel);
        map_btn_cancel.setOnClickListener(this);
        Button map_btn_add = findViewById(R.id.map_btn_add);
        map_btn_add.setOnClickListener(this);
        map_ed_high = findViewById(R.id.map_ed_high);





        /*if (Point.getSblx() != null)
            map_sp_type.setText(Point.getSblx());*/
        equId = Point.getEquipType_id();

        map_ed_high.setText(Point.getHigh());

        setSpinnerProjectelectedByValue(map_sp_state, Point.getState());
        initBoxChangeList();
        //箱变
        LiveDataBus.get().getChannel(Configuration.BoxChangeWindow, int.class).observe(this, state -> {
            initBoxChangeList();
        });
    }


    List<Line> xuanxinLine = new ArrayList<>();
    private Point Point_a, Point_b;
    private LatLng latLng_a, latLng_b;
    private RelativeLayout dis_rl_zi;
    private String aid, bid;


    List<Line> distensLines = new ArrayList<>();
    private Double length;
    RadioGroup charuType;
    RelativeLayout dis_rl_deng, dis_rl_ding;
    int selectedType = 0;
    EditText dengFen, dangJu;

    /**
     * 设置等分模式
     */
    private void setDistanceView() {
        charuType = findViewById(R.id.charuType);
        dis_rl_deng = findViewById(R.id.dis_rl_deng);
        dis_rl_ding = findViewById(R.id.dis_rl_ding);
        dengFen = findViewById(R.id.dis_ed_deng);
        dangJu = findViewById(R.id.dis_ed_ding);
        charuType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.checkMoren://默认
                        selectedType = 0;
                        dis_rl_deng.setVisibility(View.GONE);
                        dis_rl_ding.setVisibility(View.GONE);
                        break;
                    case R.id.checkFendang://等分
                        selectedType = 1;
                        dis_rl_deng.setVisibility(View.VISIBLE);
                        dis_rl_ding.setVisibility(View.GONE);
                        break;
                    case R.id.denjuModel://等距离
                        selectedType = 2;
                        dis_rl_deng.setVisibility(View.GONE);
                        dis_rl_ding.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });


    }

    /**
     * @param lngall
     */
    private void addPointAll(List<LatLng> lngall) {
        List<Point> addPoint = new ArrayList<>();
        addPoint.add(Point_a);
        for (int i = 1; i < lngall.size(); i++) {
            Point Point = new Point();
            UUID uuid = UUID.randomUUID();
            Point.setUid(uuid + "");
            Point.setHigh(Point_a.getHigh() + "");
            Point.setState(Point_a.getState());
            Point.setProjectId(id);
            Point.setLegendTypeKey(Point_a.getLegendTypeKey());

            String regEx = "[0-9]+(?=[^0-9]*$)";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(addPoint.get(addPoint.size() - 1).getMark());
            while (m.find()) {
                Point.setMark(addPoint.get(addPoint.size() - 1).getMark().replaceAll(regEx, (Integer.parseInt(m.group(0)) + 1) + ""));
            }

            Point.setEquipType_name("直线杆");
            Point.setSblx("直线杆");
            Point.setWhether("0");
            Point.setName("杆塔");
            Point.setIcon("ZXG");
            Point.setEquipType_id(1);
            Point.setDefaultLineType("1");

            Point.setLatitude(lngall.get(i).latitude);
            Point.setLongitude(lngall.get(i).longitude);
            Point.setBatch("1");//批量

            long id = App.getInstances().getDaoSession().getPointDao().insert(Point);
            ///查找关联点
            List<Equipment> equipments = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(Point_a.getId()), EquipmentDao.Properties.Qubie.eq("0")).build().list();
            if (equipments.size() > 0) {
                Equipment equipment = equipments.get(0);
                Equipment insertEquipment = new Equipment();
                insertEquipment.setName(equipment.getName());
                insertEquipment.setTwoName(equipment.getTwoName());
                insertEquipment.setThreeName(equipment.getThreeName());
                insertEquipment.setFourName(equipment.getFourName());
                insertEquipment.setQubie(equipment.getQubie());
                insertEquipment.setNote(equipment.getNote());
                insertEquipment.setPointId(id);
                insertEquipment.setAmount(equipment.getAmount());
                insertEquipment.setLever_id(equipment.getLever_id());
                insertEquipment.setHead_id(equipment.getHead_id());
                insertEquipment.setThreeId(equipment.getThreeId());
                insertEquipment.setFourId(equipment.getFourId());
                insertEquipment.setLineName(equipment.getLineName());
                insertEquipment.setModule_code(equipment.getModule_code());
                insertEquipment.setModuleID(equipment.getModuleID());
                insertEquipment.setModuleTxt(equipment.getModuleTxt());
                insertEquipment.setModuleTxt(equipment.getModuleTxt());
                insertEquipment.setProjectId(equipment.getProjectId());
                App.getInstances().getDaoSession().getEquipmentDao().insert(insertEquipment);
            }
            addPoint.add(Point);
        }
        App.getInstances().getDaoSession().getPointDao().delete(Point_b);
        Log.e(TAG, "addPointAll: " + xuanxinLine.toString());
        //按照原来线路，打断插入线路
        for (int i = 0; i < xuanxinLine.size(); i++) {
            Log.e(TAG, "addPointAll: " + addPoint.toString());
            for (int j = 1; j < addPoint.size(); j++) {
                BigDecimal bg = new BigDecimal(Distance(lngall.get(j - 1).latitude, lngall.get(j - 1).longitude, lngall.get(j).latitude, lngall.get(j).longitude)).setScale(2, RoundingMode.UP);
                double lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                //从第一个到第0个
                Line line = new Line();
                line.setLength(lengths + "");
                line.setItem_id(id);
                line.setProjectId(id);
                line.setCid(getUUID());
                line.setLatA(lngall.get(j - 1).latitude + "");
                line.setLonA(lngall.get(j - 1).longitude + "");
                line.setLatB(lngall.get(j).latitude + "");
                line.setLonB(lngall.get(j).longitude + "");
                line.setStart_id(addPoint.get(j - 1).getUid() + "");
                line.setEnd_id(addPoint.get(j).getUid() + "");
                line.setBackNum(xuanxinLine.get(i).getBackNum());
                line.setNum(xuanxinLine.get(i).getNum());
                //TODO 这里修改了    line.setType("架空线路");
                line.setType(xuanxinLine.get(i).getType());
                line.setTypeId(xuanxinLine.get(i).getTypeId());
                //int mad = (int) (lineList.get(lineList.size() - 1).getId() + 1);
                line.setState(xuanxinLine.get(i).getState());
                //选型信息
                line.setName(xuanxinLine.get(i).getName());
                line.setModuleID(xuanxinLine.get(i).getModuleID());
                line.setModuleTxt(xuanxinLine.get(i).getModuleTxt());
                line.setTypes(xuanxinLine.get(i).getTypes());
                line.setTypeId(xuanxinLine.get(i).getTypeId());
                line.setType(xuanxinLine.get(i).getType());
                line.setMethodName(xuanxinLine.get(i).getMethodName());
                line.setPath(xuanxinLine.get(i).getPath());
                line.setParallelPole(xuanxinLine.get(i).getParallelPole());

               /* if ((ps.getName().equals("杆塔") || ps.getSblx().equals("柱上变压器")) && ps.getName().equals("杆塔")) {
                    //TODO 这里修改了    line.setType("架空线路");
                    line.setLegendTypeKey(getLineRemarker("高压架空线路"));
                } else {
                    line.setLegendTypeKey(getLineRemarker("高压电缆线路"));
                }
                */
                Log.e(TAG, "addPointAll:" + line.toString());
                line.setLegendTypeKey(xuanxinLine.get(i).getLegendTypeKey());
                Long idss = App.getInstances().getDaoSession().getLineDao().insert(line);
                App.getInstances().getDaoSession().getLineDao().update(line);
            }
            App.getInstances().getDaoSession().getLineDao().delete(xuanxinLine.get(i));
        }
    }

    private Project Project;

    private Equipment getGlLine_ganxin(Line line, Point Point0) {
        Project = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().list().get(0);
        String starId = line.getStart_id();
        //先取关联杆塔选型信息
        if (starId != null && Point0.getName().equals("杆塔")) {
            Point Point = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(starId)).build().unique();
            if (Point != null && Point0.getName().equals("杆塔") && Point.getName().equals("杆塔")) {
                Equipment ganxing = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(Point.getId()), EquipmentDao.Properties.Qubie.eq(0)).build().unique();
                return ganxing;
            }
        }

        //取默认选型
        if (Project.getUnit() != null && Point0.getName().equals("杆塔")) {
            String unit = Project.getUnit();
            String[] defaultGanxing = unit.split("\\|")[0].split(",");
            /**
             *  @Id
             *     private Long id;
             *     //添加设备名称
             *     private String name;
             *     //四级各个设备名称  four_name杆高
             *     private String two_name, three_name, four_name;
             *     //区分线还是点
             *     private int qubie;
             *     //添加设备备注信息
             *     private String note;
             *     //Point的id
             *     private Long PointId;
             *     //模块的数量
             *     private int amount;
             *     //杆头，杆型的ID
             *     private String lever_id, head_id;
             *     //四级各个ID               稍径
             *     private String three_id, four_id;
             *     //线设备名称
             *     private String lineName;
             *     //设备编号
             *     private String module_code;
             *     //去module查询的id
             *     private String ModuleID;
             *     //保存时候储存的信息
             *     private String ModuleTxt;
             *     //Item_ID
             *     private Long itemID;
             */
            //Equipment{id=133, name='水泥杆', two_name='水泥杆', three_name='非预应力,整根杆,10m,190mm,I', four_name='190mm', qubie=0, note='null', PointId=142, amount=1, lever_id='50000DG', head_id='50000DG', three_id='50000', four_id='10m', lineName='null', module_code='null', ModuleID='50000', ModuleTxt='非预应力,整根杆,10m,190mm,I', itemID=19}
            if (defaultGanxing.length > 1) {
                Module defaultModel = getModuleLocal(defaultGanxing[1]);
                ModuleType defultModuleType = getModuleType(defaultGanxing[0]);
                Equipment ganxing = new Equipment();
                ganxing.setQubie(0);
                ganxing.setModuleID(defaultModel.getModuleID());
                ganxing.setModuleTxt(defaultModel.getModuleName());
                ganxing.setName(defultModuleType.getName());
                ganxing.setThreeName(defaultModel.getModuleName());
                ganxing.setModuleTxt(defaultModel.getModuleName());
                ganxing.setProjectId(Project.getId());
                ganxing.setLever_id(defaultGanxing[0]);
                ganxing.setHead_id(defaultGanxing[1]);
                //杆高和杆型 Modle表的ModuleName
                //资源文件来获取数据杆高
                String[] ganGaoArray = getResources().getStringArray(R.array.gangao_array);
                String[] ShaojingArray = getResources().getStringArray(R.array.shaojin_array);

                for (int i = 0; i < ganGaoArray.length; i++) {
                    if (defaultModel.getModuleName().contains(ganGaoArray[i])) {
                        ganxing.setFourName(ganGaoArray[i]);

                    }
                }
                for (int i = 0; i < ShaojingArray.length; i++) {
                    if (defaultModel.getModuleName().contains(ShaojingArray[i])) {
                        ganxing.setFourName(ShaojingArray[i]);

                    }
                }
                ganxing.setAmount(1);
                ganxing.setModule_code(defaultModel.getModuleCode());
                return ganxing;

            } else {
                return null;
            }
        }

        return null;
    }

    /**
     * @param
     * @return Equip
     */
    public ModuleType getModuleType(String ModuleTypeID) {
        ModuleType strings = null;
        try {
            SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
            assert db != null;
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType mt where mt.ModuleTypeID =" + "'" + ModuleTypeID + "'", null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                ModuleType equip = new ModuleType();
                equip.setModuleTypeID(cursor.getString(0));
                equip.setName(cursor.getString(1));
                equip.setModuleTypeKey(cursor.getString(2));
                strings = equip;
            }
            cursor.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return strings;
    }

    ///查询线的remark
    private Module getModuleLocal(String reMarkerName) {
        Module module_array = null;
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        Log.e("sql", "select * from Module m where m.ModuleTypeKey =" + reMarkerName);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from Module m where m.ModuleID =" + "'" + reMarkerName + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            Module module = new Module();
            module.setModuleID(cursor.getString(0));
            module.setModuleName(cursor.getString(1));
            module.setModuleTypeKey(cursor.getString(2));
            module.setModuleCode(cursor.getString(3));
            module_array = module;
        }

        cursor.close();


        return module_array;
    }

    private List<LatLng> getLatLng() {
        List<LatLng> lngall = new ArrayList<>();
        length = parseDouble(intentLine.getLength());
        if (selectedType == 1) {//等分模式
            int number = 1;
            if (!dengFen.getText().toString().trim().isEmpty()) {
                number = Integer.parseInt(dengFen.getText().toString().trim());
            }
            if (number > 200) {
                ToastUtils.showShort("一次性踩点过多");
                return lngall;
            } else {
                //等分模式：每一段都一样
                //lngall = getDengLatLng(number + 1);
                lngall = getDengLatLng(number);
            }
        } else if (selectedType == 2) {//等距离
            int number = 50;
            if (!dangJu.getText().toString().trim().isEmpty()) {
                number = Integer.parseInt(dangJu.getText().toString().trim());
            }
            if (number > length && number < 5) {
                ToastUtils.showShort("定的点距太大或太小");
                return lngall;
            } else {
                int num = (int) (length / number) + 1;
                lngall = getDengLatLng(num);
            }
        }
        return lngall;
    }

    private List<LatLng> getDengLatLng(int number) {
        double aaa, bbb, ccc = 0, ddd = 0;
        List<LatLng> latLngs = new ArrayList<>();
        Log.e("hahahaA=", latLng_a.toString());
        Log.e("hahahaB=", latLng_b.toString());

        double mlat = (latLng_b.latitude - latLng_a.latitude) / number, mlng = (latLng_b.longitude - latLng_a.longitude) / number;
        for (int i = 0; i <= number; i++) {
            aaa = latLng_a.latitude + i * mlat;
            bbb = latLng_a.longitude + i * mlng;
            LatLng latLng = new LatLng(aaa, bbb);
            Log.e("hahaha=" + i, latLng.toString());
            latLngs.add(latLng);
        }
       /* for (int i = 1; i < number + 1; i++) {
            if (latLng_a.longitude > latLng_b.longitude && latLng_a.latitude > latLng_b.latitude) {
                aaa = (latLng_a.longitude - latLng_b.longitude) / (number);
                ccc = latLng_b.longitude + aaa * (i);
                bbb = (latLng_a.latitude - latLng_b.latitude) / (number);
                ddd = bbb * (i) + latLng_b.latitude;

            } else if (latLng_a.longitude < latLng_b.longitude && latLng_a.latitude < latLng_b.latitude) {
                aaa = (latLng_b.longitude - latLng_a.longitude) / (number);
                ccc = latLng_a.longitude + aaa * (i);
                bbb = (latLng_b.latitude - latLng_a.latitude) / (number);
                ddd = latLng_a.latitude + bbb * i;

            } else if (latLng_a.longitude > latLng_b.longitude && latLng_a.latitude < latLng_b.latitude) {
                aaa = (latLng_a.longitude - latLng_b.longitude) / (number);
                ccc = latLng_b.longitude + aaa * (number - i);
                bbb = (latLng_b.latitude - latLng_a.latitude) / (number);
                ddd = latLng_a.latitude + bbb * i;

            } else if (latLng_a.longitude < latLng_b.longitude && latLng_a.latitude > latLng_b.latitude) {
                aaa = (latLng_b.longitude - latLng_a.longitude) / (number);
                ccc = latLng_a.longitude + aaa * (i);
                bbb = (latLng_a.latitude - latLng_b.latitude) / (number);
                ddd = latLng_a.latitude - bbb * i;

            }

            latLngs.add(new LatLng(ddd, ccc));
        }*/
        return latLngs;
    }

    //主杆塔。副杆塔
    private void getZFganView() {
        List<Point> zfgPoint = getAllPoint();
        ArrayAdapter<Point> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, zfgPoint);
        //设置样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        zhuGanSpinner.setAdapter(adapter);

        fuGanSpinner.setAdapter(adapter);

        for (int i = 1; i < zfgPoint.size(); i++) {
            if (ps.getLonA() != null && zfgPoint.get(i).getUid().equals(ps.getLonA())) {
                zhuGanSpinner.setSelection(i);
                break;
            }
        }

        fuGanSpinner.setAdapter(adapter);
        for (int i = 1; i < zfgPoint.size(); i++) {
            if (ps.getLonB() != null && zfgPoint.get(i).getUid().equals(ps.getLonB())) {
                fuGanSpinner.setSelection(i);
                break;
            }
        }

    }

    List<Point> getAllPoint() {
        List<Point> PointZFGan = new ArrayList<>();
        Point Point = new Point();
        Point.setName("");
        Point.setMark("请选择");
        PointZFGan.add(Point);
        List<Point> allPoint = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(ps.getProjectId() + ""), PointDao.Properties.Name.eq("杆塔")).build().list();
        Log.e("allPoint", allPoint.toString() + "======" + Point.getProjectId() + "");
        PointZFGan.addAll(allPoint);
        return PointZFGan;

    }

    List<Module> modulesList = new ArrayList<>();
    private Equip equip;


    List<Line> xuanxinList = new ArrayList<>();
    RecyclerView.Adapter linesAdapter;
    RecyclerView mLineListView;
    LinearLayout lineLuMokuai;

    private void setLineXuanxing() {
        mLineListView = findViewById(R.id.mLineListView);
        lineLuMokuai = findViewById(R.id.lineLuMokuai);

        addLineSave = findViewById(R.id.addLineSave);
        List<Point> allPoint = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(id)).build().list();
        if (allPoint.size() <= 1) {
            lineLuMokuai.setVisibility(View.GONE);
        }
        /*if (intentLine != null) {
            xuanxinList.add(intentLine);
        } else {*/
        List<Point> PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(id)).build().list();
        List<String> adapter_data = new ArrayList<>();
        for (int i = 0, len = PointList.size() - 1; i < len; i++) {
            if (PointList.get(i).getMark() != null && !PointList.get(i).getMark().equals("")) {
                adapter_data.add(PointList.get(i).getMark());
            } else {
                adapter_data.add("未命名");
            }
        }
        /**
         * 关联
         */
        //设置样式
        String glsbUId = "";
        List<Line> gulianLine = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.End_id.eq(Point.getUid())).build().list();
        if (gulianLine.size() > 0) {
            List<Point> guanLinePoint = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(gulianLine.get(0).getStart_id())).build().list();
            if (guanLinePoint.size() > 0) {
                List<Line> currenPointLine = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.End_id.eq(Point.getUid()), LineDao.Properties.Start_id.eq(guanLinePoint.get(0).getUid())).build().list();
                xuanxinList.addAll(currenPointLine);
            }

        } else {
            lineLuMokuai.setVisibility(View.GONE);

        }
//        if (xuanxinList.size() >= 3) {
//            addLineSave.setVisibility(View.GONE);
//        } else {
//            addLineSave.setVisibility(View.VISIBLE);
//
//        }
//        addLineSave.setOnClickListener(v -> {
//            if (xuanxinList.size() > 0) {
//                Line LineWf = xuanxinList.get(0);
//                Line newLineWf = new Line();
//                newLineWf.setCid(getUUID());
//                newLineWf.setStart_id(LineWf.getStart_id());
//                newLineWf.setEnd_id(LineWf.getEnd_id());
//                //newLineWf.setName(LineWf.getName());
//                newLineWf.setType(LineWf.getType());
//                newLineWf.setTypes(LineWf.getTypes());
//                newLineWf.setPipe_laying_state(LineWf.getPipe_laying_state());
//                newLineWf.setState(LineWf.getState());
//                newLineWf.setTypeId(LineWf.getTypeId());
//                newLineWf.setBackNum(LineWf.getBackNum());
//                newLineWf.setNum(LineWf.getNum());
//                newLineWf.setMethodName(LineWf.getMethodName());
//                newLineWf.setLine_len(LineWf.getLine_len());
//                newLineWf.setItem_id(LineWf.getItem_id());
//                newLineWf.setLatA(LineWf.getLatA());
//                newLineWf.setLatB(LineWf.getLatB());
//                newLineWf.setLonA(LineWf.getLonA());
//                newLineWf.setLonB(LineWf.getLonB());
//                newLineWf.setName_a(LineWf.getName_a());
//                newLineWf.setName_b(LineWf.getName_b());
//                newLineWf.setLength(LineWf.getLength());
//                newLineWf.setModuleID(LineWf.getModuleID());
//                newLineWf.setPath(LineWf.getPath());
//                newLineWf.setName_b(LineWf.getName_b());
//                newLineWf.setLength(LineWf.getLength());
//                newLineWf.setModuleID(LineWf.getModuleID());
//                newLineWf.setModuleTxt(LineWf.getModuleTxt());
//                newLineWf.setPath(LineWf.getPath());
//                if (LineWf.getLegendTypeKey() == null || LineWf.getLegendTypeKey().isEmpty()) {
//                    newLineWf.setLegendTypeKey(getLineRemarker("高压架空线路"));
//
//                } else {
//                    newLineWf.setLegendTypeKey(LineWf.getLegendTypeKey());
//                }
//                //这里计算所有的线路名称
//                //获取所有的线路去除过同样名称的个数就是所有线的编号。获取整个工程中的最大的数据并数字+1
//                /*List<String>unitAllLine=new ArrayList<>();
//                List<Line> allLine = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(id)).list();
//                for (int i = 0; i < allLine.size(); i++) {
//                    if(!unitAllLine.contains(allLine.get(i).getName())){
//                        unitAllLine.add(allLine.get(i).getName());
//                    }
//                }*/
//                String line_names = "线路" + LineUtils.getInstance().getInLinesMaxNumber(id) + "#";
//                newLineWf.setName(line_names);
//                long currentId = App.getInstances().getDaoSession().getLineDao().insert(newLineWf);
//                newLineWf.setId(currentId);
//                //newLineWf.setName(currentId + "#");
//                App.getInstances().getDaoSession().getLineDao().update(newLineWf);
//                xuanxinList.add(newLineWf);
//                buiLuNameber.setText(xuanxinList.size() + "回路");
//                mHandler.postDelayed(() -> linesAdapter.notifyDataSetChanged(), 200);
//                if (xuanxinList.size() >= 3) {
//                    addLineSave.setVisibility(View.GONE);
//                } else {
//                    addLineSave.setVisibility(View.VISIBLE);
//
//                }
//
//            }
//        });
//        buiLuNameber.setText(xuanxinList.size() + "回路");
        buiLuNameber.setText(Point.getRoadName() + " 1#");
        linesAdapter = new LinesAdapter();
        mLineListView.setAdapter(linesAdapter);
        linesAdapter.notifyDataSetChanged();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mLineListView.setLayoutManager(linearLayoutManager);


    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //若工作完成，取消动画，初始化界面

        }
    };

    @Override
    public void Result(@NotNull String result) {
        Log.e(TAG, "Result:" + result);
        if (!result.isEmpty() && progress_Et != null)
            progress_Et.setText(result);
    }

    class LinesAdapter extends RecyclerView.Adapter<LinesAdapter.ViewHolder> {
        /*   @Override
           public int getCount() {
               return xuanxinList.size() > 0 ? xuanxinList.size() : 0;
           }

           @Override
           public Object getItem(int position) {

               return xuanxinList.get(position);
           }
   */
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View convertView = LayoutInflater.from(context).inflate(R.layout.activity_lines_item, null);
            return new ViewHolder(convertView);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
            viewHolder.lineXuanxing.setText((xuanxinList.get(position).getTypes() == null || xuanxinList.get(position).getTypes().isEmpty()) ? "设置值" : xuanxinList.get(position).getTypes());
            viewHolder.lineStateTv.setText(xuanxinList.get(position).getState());
            viewHolder.lineNameTv.setText(xuanxinList.get(position).getName());
            if (xuanxinList.get(position).getType() != null && !xuanxinList.get(position).getType().isEmpty()) {
                viewHolder.lineLiebieTv.setText(xuanxinList.get(position).getType().replace("线路", ""));
            }
            if (xuanxinList.size() > 0) {
                Log.e("ponslgjlsjg", xuanxinList.toString());
                Point ptA = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(xuanxinList.get(position).getStart_id())).build().unique();
                Point ptB = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(xuanxinList.get(position).getEnd_id())).build().unique();
                if (ptA != null && ptA.getName() != null && ptA.getMark() != null) {
                    viewHolder.lineGlName.setText("始：" + ptA.getMark());
                    viewHolder.linezGlName.setText("终：" + ptB.getMark());

                }
                if (xuanxinList.get(position).getParallelPole() != null && xuanxinList.get(position).getParallelPole().equals("同杆并架")) {
                    viewHolder.tongganBingjia.setText(xuanxinList.get(position).getParallelPole());
                }
                viewHolder.lineGlDangjuName.setText(xuanxinList.get(position).getLength());

                viewHolder.xiugaiTv.setOnClickListener(v -> xiugaiLinePopWindows(xuanxinList.get(position)));
                if (xuanxinList.size() > 1) {
                    viewHolder.xiugaiDeTv.setVisibility(View.VISIBLE);

                } else {
                    viewHolder.xiugaiDeTv.setVisibility(View.GONE);

                }
                viewHolder.xiugaiDeTv.setOnClickListener(v -> {
                    if (xuanxinList.size() > 1) {
                        final NormalDialog dialog = new NormalDialog(EquActivity.this);
                        dialog.content("确定删除?")//
                                .style(NormalDialog.STYLE_TWO)//
                                .btnNum(2)
                                .title("删除线选型")
                                .btnText("取消", "删除")//
                                .show();
                        dialog.setOnBtnClickL(
                                dialog::dismiss, () -> {
                                    dialog.dismiss();
                                    App.getInstances().getDaoSession().getLineDao().delete(xuanxinList.get(position));
                                    xuanxinList.remove(xuanxinList.get(position));
//                                    if (xuanxinList.size() >= 3) {
//                                        addLineSave.setVisibility(View.GONE);
//                                    } else {
//                                        addLineSave.setVisibility(View.VISIBLE);
//
//                                    }
//                                    buiLuNameber.setText(xuanxinList.size() + "回路");
                                    buiLuNameber.setText(Point.getRoadName() + " 1#");
                                    notifyDataSetChanged();
                                });

                    } else {
                        ToastUtils.showShort("不能删除");
                    }
                });
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            return xuanxinList == null ? 0 : xuanxinList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView lineXuanxing, lineStateTv, lineNameTv, lineLiebieTv;
            TextView xiugaiTv, xiugaiDeTv, lineState, lineGlName, lineGlDangjuName, linezGlName, tongganBingjia;

            public ViewHolder(@NonNull View rootView) {
                super(rootView);
                lineXuanxing = rootView.findViewById(R.id.lineXuanxing);
                lineStateTv = rootView.findViewById(R.id.lineState);
                lineNameTv = rootView.findViewById(R.id.lineName);
                lineLiebieTv = rootView.findViewById(R.id.lineLiebie);
                xiugaiTv = rootView.findViewById(R.id.xiugaiTv);
                xiugaiDeTv = rootView.findViewById(R.id.xiugaiDeTv);
                linezGlName = rootView.findViewById(R.id.linezGlName);
                //lineState = rootView.findViewById(R.id.lineState);
                lineGlName = rootView.findViewById(R.id.lineGlName);
                lineGlDangjuName = rootView.findViewById(R.id.lineGlDangjuName);
                tongganBingjia = rootView.findViewById(R.id.tongganBingjia);


            }
        }
    }


    //TODO
    Spinner currentLineSort;
    Spinner currentLineType;
    Spinner currentLineSate;
    EditText currentLineName;


    private Spinner line_sp_sort;
    private Spinner line_sp_type;
    private Spinner line_sp_statue;
    private Spinner line_sp_a;
    private Spinner line_stf_a;
    private Spinner line_sp_b;
    private Spinner line_tongdao_statue;
    private EditText line_tv_dj;
    private EditText line_tv_line_hui;
    private EditText line_tv_line_gen;
    private EditText zjcjgTv;
    private Line currentLine;
    private List<ModuleType> allMT = new ArrayList<>();
    private Spinner lineSpLaying;
    private RelativeLayout lineRlLaying;
    private EditText lineTvName;
    private Button map_btn_cancell, line_btn_save;
    private String fenzhiLineId = "";
    List<Line> guanLiTLine = null;




    private  Spinner srcNetureSpiner;
    private Spinner  srcNetureTypeSpiner;


    private EditText roadZcEt;
    private EditText roadAdress;
    private TextView resultCaculateHols;
    private TextView resultHolesTv;
    private TextView numberOfPowerHoles;

    private EditText lineNumberEt;
    private EditText shenyuNumber;
    private Spinner srcStateSp;
    private EditText ghYear;
    private TextView roadStarTv;
    private TextView roadEndTv;
    private TextView gridNameLineEt;
    private void xiugaiLinePopWindows(Line isLine) {
        View viewLine = View.inflate(context, R.layout.line_type_xiugai, null);
        TextView equ_btn_equ = viewLine.findViewById(R.id.equ_btn_equ);
        equ_btn_equ.setOnClickListener(this);
        lineTvName = viewLine.findViewById(R.id.lineTvName);
        map_btn_cancell = viewLine.findViewById(R.id.map_btn_cancell);
        line_btn_save = viewLine.findViewById(R.id.line_btn_save);
        lineSpLaying = viewLine.findViewById(R.id.lineSpLaying);
        lineRlLaying = viewLine.findViewById(R.id.lineRlLaying);
        line_sp_sort = viewLine.findViewById(R.id.line_sp_sort);
        line_sp_type = viewLine.findViewById(R.id.line_sp_type);
        line_sp_statue = viewLine.findViewById(R.id.line_sp_statue);
        line_sp_a = viewLine.findViewById(R.id.line_sp_a);
        line_stf_a = viewLine.findViewById(R.id.line_stf_a);
        relatRt = viewLine.findViewById(R.id.relatRt);
        line_sp_b = viewLine.findViewById(R.id.line_sp_b);
        line_tv_dj = viewLine.findViewById(R.id.line_tv_dj);
        line_tongdao_statue = viewLine.findViewById(R.id.line_tongdao_statue);
        line_tv_line_hui = viewLine.findViewById(R.id.line_tv_line_hui);
        line_tv_line_gen = viewLine.findViewById(R.id.line_tv_line_gen);





        //region湖南
         roadStarTv = viewLine.findViewById(R.id.roadStarTv);
         roadEndTv  = viewLine.findViewById(R.id.roadEndTv);
        roadAdress = viewLine.findViewById(R.id.roadAdress);
        roadZcEt = viewLine.findViewById(R.id.roadZcEt);
        zjcjgTv=viewLine.findViewById(R.id.zjcjgTv);
        srcNetureTypeSpiner = viewLine.findViewById(R.id.srcNetureTypeSpiner);
        srcNetureSpiner = viewLine.findViewById(R.id.srcNetureSpiner);
        resultCaculateHols = viewLine.findViewById(R.id.resultCaculateHols);
        resultHolesTv      = viewLine.findViewById(R.id.resultHolesTv);
        numberOfPowerHoles = viewLine.findViewById(R.id.numberOfPowerHoles);
        gridNameLineEt=viewLine.findViewById(R.id.gridNameLineEt);
        lineNumberEt = viewLine.findViewById(R.id.lineNumberEt);
        shenyuNumber = viewLine.findViewById(R.id.shenyuNumber);
        srcStateSp   = viewLine.findViewById(R.id.srcStateSp);
        ghYear   = viewLine.findViewById(R.id.ghYear);
        LinearLayout yearHindLt=viewLine.findViewById(R.id.yearHindLt);



        if (isLine.getStart_id() != null) {
            List<Point>listPoins= App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(isLine.getStart_id())).list();
            if (!listPoins.isEmpty()){
                roadStarTv.setText(listPoins.get(0).getMark());
            }

            List<Point>listPoinsEnd=  App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(isLine.getEnd_id())).list();
            if (!listPoinsEnd.isEmpty()){
                roadEndTv.setText(listPoinsEnd.get(0).getMark());
            }
            //网格名称
            gridNameLineEt.setText(isLine.getModuleTxt().equals("") ? listPoinsEnd.get(0).getGridName() : isLine.getModuleTxt());
            //名称
            if (isLine.getName()!=null){
                lineTvName.setText(listPoinsEnd.get(0).getRoadName());
            }
            //道路主次路
            if (isLine.getRoadPands()!=null){
                roadZcEt.setText(isLine.getRoadPands());
            }
            //电缆支架规格（架长*间距*高度）
            if(isLine.getDlzjSpec()!=null){
                zjcjgTv.setText(isLine.getDlzjSpec());
            }
            //道路位置
            roadAdress.setText(isLine.getRoadAdress() == null ? listPoinsEnd.get(0).getRoadAdress() : isLine.getRoadAdress());
            //已占用数量
            if (isLine.getArdUseNumer()!=null){
                lineNumberEt.setText(isLine.getArdUseNumer());
            }
            //电力孔数
            if (isLine.getElectriHoleNumer()!=null){
                numberOfPowerHoles.setText(isLine.getElectriHoleNumer());
            }
            if (isLine.getRemaNumber()!=null){
                shenyuNumber.setText(isLine.getRemaNumber());
            }
            if (isLine.getRoadUtili()!=null){
                resultHolesTv.setText(isLine.getRoadUtili());
            }
            if (isLine.getSrcYear()!=null){
                ghYear.setText(isLine.getSrcYear());
            }


            String[] arrayListRs = getResources().getStringArray(R.array.linsrcTypeArray);
            for (int selecteIndex = 0; selecteIndex < arrayListRs.length; selecteIndex++) {
                if (isLine.getResType() == null) {
                    srcNetureTypeSpiner.setSelection(0);
                    break;
                }
                if (arrayListRs[selecteIndex].equals(isLine.getResType())) {
                    srcNetureTypeSpiner.setSelection(selecteIndex);
                    break;
                }
            }
            srcNetureTypeSpiner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    initSrcGuiGe(arrayListRs[position], isLine);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        }

        String[] arrayListRs = getResources().getStringArray(R.array.srState);
        for (int selecteIndex = 0; selecteIndex < arrayListRs.length; selecteIndex++) {
            if (isLine.getState() == null) {
                srcStateSp.setSelection(0);
                break;
            }
            if (arrayListRs[selecteIndex].equals(isLine.getState())) {
                srcStateSp.setSelection(selecteIndex);
                break;
            }
        }

        srcStateSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (arrayListRs[position].equals("规划态")) {
                    yearHindLt.setVisibility(View.VISIBLE);
                } else {
                    yearHindLt.setVisibility(View.GONE);

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        resultCaculateHols.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(lineNumberEt.getText()==null)&& !shenyuNumber.getText().toString().isEmpty()) {
                    String str = format1(Double.parseDouble(lineNumberEt.getText().toString()) / (Integer.parseInt(lineNumberEt.getText().toString()) + Integer.parseInt(shenyuNumber.getText().toString())));
                    resultHolesTv.setText(str);
                }
            }
        });

        //endregion











        line_tv_line_hui.setText(isLine.getBackNum());
        line_tv_dj.setText((isLine.getLength() != null ? isLine.getLength() : "" )+ "米");
        List<Equip> equipList = getGuPiaoDai(3);
        //适配器
        ArrayAdapter<Equip> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, equipList);
        //设置样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        line_sp_sort.setAdapter(adapter);
        if (line_sp_sort.getSelectedItem().toString().contains("电缆")) {
            lineRlLaying.setVisibility(View.VISIBLE);
        } else {
            lineRlLaying.setVisibility(View.GONE);
        }
        for (int i = 0; i < equipList.size(); i++) {
            if (isLine.getType() != null && (equipList.get(i).getName().equals(isLine.getType()) || equipList.get(i).getName().contains(isLine.getType()))) {
                line_sp_sort.setSelection(i);
                break;
            }
        }
        if (isLine.getState() != null && !isLine.getState().isEmpty()) {
            setSpinnerProjectelectedByValue(line_sp_statue, isLine.getState());
        }
        if (isLine.getPipe_laying_state() != null && !isLine.getPipe_laying_state().isEmpty()) {
            setSpinnerProjectelectedByValue(line_tongdao_statue, isLine.getPipe_laying_state());
        }
        if (isLine.getPath() != null && !isLine.getPath().equals("")) {
            String[] linePath = getResources().getStringArray(R.array.laying);
            for (int i = 0; i < linePath.length; i++) {
                if (linePath[i].contains(isLine.getPath().trim())) {
                    lineSpLaying.setSelection(i);
                    //选中之后进行不同类别。


                    break;
                }
            }
        } else {
            setSpinnerProjectelectedByValue(lineSpLaying, "高压架空线路");
            line_tv_line_gen.setText("3");
            line_tv_line_gen.setEnabled(false);

        }


        line_sp_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                equip = ((Equip) line_sp_sort.getSelectedItem());
                modulesList = getModuleList(equip.getId());
                //适配器
                ArrayAdapter<Module> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, modulesList);
                arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                line_sp_type.setAdapter(arr_adapter4);
                if (isLine.getTypes() != null) {
                    for (int i = 0; i < modulesList.size(); i++) {
                        if (modulesList.get(i).getModuleName().contains(isLine.getTypes())) {
                            line_sp_type.setSelection(i);
                            break;
                            //setSpinnerItemSelectedByValue(line_sp_type, isLine.getTypes());

                        }

                    }
                }
                if (line_sp_sort.getSelectedItem().toString().contains("电缆")) {
                    lineRlLaying.setVisibility(View.VISIBLE);
                } else {
                    lineRlLaying.setVisibility(View.GONE);
                }

                if (equip.getName().equals("高压架空线路")) {
                    line_tv_line_gen.setText("3");
                    line_tv_line_gen.setEnabled(true);

                } else if (equip.getName().equals("低压架空线路")) {
                    line_tv_line_gen.setText("4");
                    line_tv_line_gen.setEnabled(true);
                } else if (equip.getName().contains("电缆")) {
                    line_tv_line_gen.setText("1");
                    line_tv_line_gen.setEnabled(true);
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        line_sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //如果是电缆，显示敷设方式。否则不显示
                if (modulesList.get(position).getRemark() != null && !modulesList.get(position).getRemark().equals("")) {
                    setSpinnerItemSelectedByValue(lineSpLaying, modulesList.get(position).getRemark());
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //lineTvName.setText(isLine.getName());

        if (isLine.getItem_id() != null) {

            List<Point> PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(isLine.getItem_id())).build().list();
            //适配器
            ArrayAdapter<Point> sp_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, PointList);
            sp_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            line_sp_a.setAdapter(sp_adapter);
            line_sp_b.setAdapter(sp_adapter);
            Point ptA = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(isLine.getStart_id())).build().unique();
            Point ptB = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(isLine.getEnd_id())).build().unique();
            if (ptA != null) {
                for (int i = 0; i < line_sp_a.getAdapter().getCount(); i++) {
                    Point spA = (Point) line_sp_a.getAdapter().getItem(i);
                    if (ptA.getUid().equals(spA.getUid())) {
                        line_sp_a.setSelection(i, true);
                    }
                }
            }
            if (ptB != null) {
                for (int i = 0; i < line_sp_b.getAdapter().getCount(); i++) {
                    Point spB = (Point) line_sp_b.getAdapter().getItem(i);
                    if (ptB.getUid().equals(spB.getUid())) {
                        line_sp_b.setSelection(i, true);
                    }
                }
            }
            /*


            if (ptA != null && ptA.getName() != null && ptA.getMark() != null) {
                setSpinnerProjectelectedByValue(line_sp_a, ptA.getName() + ptA.getMark());
            }
            if (ptB != null && ptB.getName() != null && ptB.getMark() != null) {
                setSpinnerProjectelectedByValue(line_sp_b, ptB.getName() + ptB.getMark());
            }*/

        }
        //关联分支线
        if (isLine.getFenZhiLineId() != null && !isLine.getFenZhiLineId().isEmpty()) {
            relatRt.setVisibility(View.VISIBLE);
            guanLiTLine = getGuanLine(isLine);
        }
        if (guanLiTLine != null) {
            //适配器
            ArrayAdapter<Line> guanlianAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, guanLiTLine);
            line_stf_a.setAdapter(guanlianAdapter);
            for (int i = 0; i < guanLiTLine.size(); i++) {
                Log.e(TAG, "xiugaiLinePopWindows: " + guanLiTLine.get(i).toString1());
                Log.e(TAG, "xiugaiLinePopWindowss: " + isLine.getFenZhiLineId());//c5386b91-002f-4e9a-8308-4b8c5d24c482
                //c5386b91-002f-4e9a-8308-4b8c5d24c482
                if (guanLiTLine.get(i).getCid() != null && guanLiTLine.get(i).getCid().equals(isLine.getFenZhiLineId().trim())) {
                    Log.e(TAG, "xiugaiLinePopWindowssindex: " + i);
                    line_stf_a.setSelection(i);
                    break;
                }
            }
            List<Line> finalGuanLiTLine = guanLiTLine;
            line_stf_a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    fenzhiLineId = finalGuanLiTLine.get(position).getCid();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        }
        //显示柱上设备模态弹窗
        AlertDialog dialogFushu = new AlertDialog.Builder(context).create();
        dialogFushu.setView(viewLine);
        map_btn_cancell.setOnClickListener(v -> {
            dialogFushu.dismiss();
        });
        line_btn_save.setOnClickListener(v -> {
            if (lineTvName.getText().toString().trim().isEmpty() || lineTvName.getText().toString().trim().equals("") || lineTvName.getText() == null) {
                ToastUtils.showShort("请输入线路名称");
            } else {
                if (lineTvName.getText().toString().trim().equals(isLine.getName())) {
                    saveLine(isLine, false);
                    dialogFushu.dismiss();

                } else {
                    dialogFushu.dismiss();
                    final NormalDialog dialog = new NormalDialog(EquActivity.this);
                    dialog.content("修改整个线路名称为:" + "'" + lineTvName.getText().toString().trim() + "'")//
                            .style(NormalDialog.STYLE_TWO)//
                            .btnNum(3)
                            .title("是否修改整条线路?")
                            .btnText("取消", "是", "否")//
                            .show();
                    dialog.setOnBtnClickL(
                            dialog::dismiss, () -> {
                                dialog.dismiss();
                                saveLine(isLine, true);
                                dialogFushu.dismiss();
                            }, () -> {
                                dialog.dismiss();
                                saveLine(isLine, false);
                                dialogFushu.dismiss();
                            });
                }


            }
        });
        dialogFushu.show();


    }

    private void initSrcGuiGe(String value, Line isLine) {
            String[] arrayListRs;
            if (value.equals("电缆沟")) {
                arrayListRs = getResources().getStringArray(R.array.dlgArray);

            } else {
                arrayListRs = getResources().getStringArray(R.array.paiZmArray);
            }
            //适配器
            ArrayAdapter<String>  srcArrayAdapter =new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayListRs);
            //设置样式
            srcArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            srcNetureSpiner.setAdapter(srcArrayAdapter);
            for (int selecteIndex = 0; selecteIndex <arrayListRs.length ; selecteIndex++) {
                if (isLine.getResSpec() == null) {
                    srcNetureSpiner.setSelection(0);
                    break;
                }
                if (arrayListRs[selecteIndex].equals(isLine.getResSpec())) {
                    srcNetureSpiner.setSelection(selecteIndex);
                    break;
                }
            }

    }

    private List<Line> getGuanLine(Line isLine) {
        //找到这个线的起始点就是分支杆塔
        Point guanPoint = getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(isLine.getStart_id())).unique();
        //获取线的结束id是杆塔的此杆塔的所有的线才ok
        if (guanPoint == null) {
            return null;
        }
        List<Line> allTAbout = getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.End_id.eq(guanPoint.getUid())).build().list();
        for (int i = 0; i < allTAbout.size(); i++) {
            for (int j = 0; j < allTAbout.size(); j++) {
                if (i != j && allTAbout.get(i).getName().equals(allTAbout.get(j).getName())) {
                    allTAbout.remove(j);
                    j--;
                }
            }
        }
        return allTAbout;
    }
    private void saveLine(Line isLine, boolean allAlert) {
        String allLineName = isLine.getName();
        if (zjcjgTv.getText()==null||zjcjgTv.getText().toString().isEmpty()) {
            ToastUtils.showShort("请输入电缆支架规格");
            return;
        }
        if (lineTvName.getText().toString().trim().isEmpty() || lineTvName.getText().toString().trim().equals("") || lineTvName.getText() == null) {
            ToastUtils.showShort("请输入线路名称");
        } else {
            Point ptA = (Point) line_sp_a.getSelectedItem();
            Point ptB = (Point) line_sp_b.getSelectedItem();
            //Point{id=135, equ_id=1, high='4.9E-324', old='新建', lineType='ZXG-1', DefaultLineType='1', linetype='null', ProjectId=18, note='', mark='ZXG-1', sbbh='直线杆', sbzt='null', glsb='', lat='31.04502384846852', lon='112.22537799999994', weizhi='TY_SNG', dangju=0.0, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='98cfff5a-1bc6-456d-a59f-78275b7a1524', length='null', width='null', icon='ZXG', address='null'}
            //Point{id=137, equ_id=1, high='4.9E-324', old='新建', lineType='ZXG-3', DefaultLineType='1', linetype='null', ProjectId=18, note='', mark='ZXG-3', sbbh='直线杆', sbzt='null', glsb='ZXG-2', lat='31.047256446249175', lon='112.23016046697691', weizhi='TY_SNG', dangju=272.21, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='fc951730-6815-4495-b165-44ac4a9f65f0', length='null', width='null', icon='ZXG', address='null'}
            Module selMod = (Module) line_sp_type.getSelectedItem();

            isLine.setType(line_sp_sort.getSelectedItem().toString() + "");//setType
            if (line_sp_type.getSelectedItem() != null && !line_sp_type.getSelectedItem().equals("")) {
                isLine.setTypes(line_sp_type.getSelectedItem().toString() + "");
            }
            if (equip != null) {
                isLine.setTypeId(equip.getId() + "");
            }
            isLine.setLegendTypeKey(getLineRemarker(line_sp_sort.getSelectedItem() + ""));


            /**
             * Line{id=384, start_id='92556194-4a2f-4c47-9d4c-2292748c9459', end_id='b060c54d-2643-48af-a117-d53e172bf5f9',
             * name='384#', type='高压电缆线路', types='ZC-YJY22-10kV-3*400,无阻水', versionName='null', statue='新建', type_Id='394',
             * backNum='1', num='1', methodName='高压电缆线路', line_len='null', item_id=79, latA='31.043728920790404',
             * latB='31.044088590715972', lonA='112.22473724942175', lonB='112.22476480659155', name_a=0, name_b=0,
             * length='41', ModuleID='13', ModuleTxt='ZC-YJY22-10kV-3*400,无阻水', path='排管', parallelPole='null'}]
             */
            isLine.setCid(getUUID());
            isLine.setState(line_sp_statue.getSelectedItem().toString().trim());
            isLine.setPipe_laying_state(line_tongdao_statue.getSelectedItem().toString().trim());//通道信息里面的状态。
            isLine.setLatA(ptA.getLatitude() + "");
            isLine.setLonA(ptA.getLongitude() + "");
            isLine.setLatB(ptB.getLatitude() + "");
            isLine.setLonB(ptB.getLongitude() + "");
            //}
            if (gridNameLineEt.getText()!=null&&gridNameLineEt.getText().toString().isEmpty()){
                ToastUtils.showLong("网格名称不能为空");
                return;
            }else{
                isLine.setModuleTxt(gridNameLineEt.getText().toString());
            }
            isLine.setName(lineTvName.getText().toString());
            isLine.setMethodName(line_sp_sort.getSelectedItem() + "");

            isLine.setStart_id(ptA.getUid() + "");
            isLine.setEnd_id(ptB.getUid() + "");
            if (!fenzhiLineId.isEmpty()) {
                Log.e("fenzhilineId==", fenzhiLineId);
                isLine.setFenZhiLineId(fenzhiLineId);
            }
            //重新计算档距
            //currentLine.setLength(String.format("%.2f", Distance(ptA.getLat(), ptA.getLon(), ptB.getLat(), ptB.getLon())));
            isLine.setLength(line_tv_dj.getText().toString());
            if (!line_tv_line_hui.getText().toString().trim().equals("")) {
                isLine.setBackNum(line_tv_line_hui.getText().toString().trim());
            } else {
                isLine.setBackNum("1");
            }

            if (!line_tv_line_gen.getText().toString().trim().equals("")) {
                isLine.setNum(line_tv_line_gen.getText().toString().trim());
            } else {
                isLine.setNum("1");
            }

            if (selMod != null) {
                isLine.setModuleID(selMod.getModuleID());
                isLine.setModuleTxt(selMod.getModuleName());
            }
            //敷设保存地方
            if (lineSpLaying.getSelectedItem() != null && !lineSpLaying.getSelectedItem().toString().equals("") && lineSpLaying.getVisibility() == View.VISIBLE) {
                isLine.setPath(lineSpLaying.getSelectedItem().toString());
            }


            //道路主次路
            isLine.setRoadPands(roadZcEt.getText().toString());
            isLine.setDlzjSpec(zjcjgTv.getText().toString());
            isLine.setRoadAdress(roadAdress.getText().toString());
            isLine.setArdUseNumer(lineNumberEt.getText().toString());
            isLine.setElectriHoleNumer(numberOfPowerHoles.getText().toString());
            isLine.setRemaNumber(shenyuNumber.getText().toString());
            isLine.setRemaNumber(shenyuNumber.getText().toString());
            isLine.setRoadUtili(resultHolesTv.getText().toString());
            isLine.setSrcYear(ghYear.getText().toString());
            isLine.setResType(srcNetureTypeSpiner.getSelectedItem().toString());
            isLine.setResSpec(srcNetureSpiner.getSelectedItem().toString());
            if (lineNumberEt.getText()!=null && !shenyuNumber.getText().toString().isEmpty()) {
                String srcUFil= format1(Double.parseDouble(lineNumberEt.getText().toString()) / (Integer.parseInt(lineNumberEt.getText().toString()) + Integer.parseInt(shenyuNumber.getText().toString())));
                isLine.setRoadUtili(srcUFil);
            }
            //endRegion




            App.getInstances().getDaoSession().getLineDao().update(isLine);

            //这里去更新所有线路里面的所有的名称相同的线路名称
            if (allAlert) {
                List<Line> lineAllNameSame = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Name.eq(allLineName)).build().list();
                for (Line l : lineAllNameSame) {
                    l.setName(lineTvName.getText().toString());
                    App.getInstances().getDaoSession().getLineDao().update(l);

                }
            }

            //TODO Once修改一整条线路，根据“拐点”判断是否为一条线
            /*Set<Line> lineS = getRelationLine(isLine, false);
            for (Line l : lineS) {
                l.setModuleID(isLine.getModuleID());
                l.setModuleTxt(isLine.getModuleTxt());
                l.setName(isLine.getName());
                l.setType(isLine.getType());
                l.setTypes(isLine.getTypes());
                l.setType_Id(isLine.getType_Id());
                l.setLegendTypeKey(isLine.getLegendTypeKey());
                l.setNum(isLine.getNum());
                l.setBackNum(isLine.getBackNum());
                l.setStatue(isLine.getState());
                App.getInstances().getDaoSession().getLineDao().update(l);
            }*/
        }
        xuanxinList.clear();
        setLineXuanxing();
    }

    private String format1(Double value) {
        BigDecimal bd =new BigDecimal(value * 100);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        return bd.toString();
    }
    /**
     * 添加附属设备
     */
    @SuppressLint("SetTextI18n")
    private void addFushuZhuzhang(Equipment equip, int quebie) {
        final View views = View.inflate(context, R.layout.activity_equ_dialog, null);
        final Spinner map_ed_lever = views.findViewById(R.id.map_ed_lever);
        final Spinner map_ed_head = views.findViewById(R.id.map_ed_head);
        final Spinner map_sp_three = views.findViewById(R.id.map_sp_three);
        final EditText map_ed_four = views.findViewById(R.id.map_ed_four);
        final EditText map_ed_bh = views.findViewById(R.id.map_ed_bh);
        TextView mapTvNum = views.findViewById(R.id.mapTvNum);
        Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
        Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
        TextView map_tv_title = views.findViewById(R.id.map_tv_title);

        if (Point.getSblx().equals("电缆保护管")) {
            map_ed_four.setHint("距离（米）");
            mapTvNum.setText("设备长度");
        }
        if (quebie == 2) {
            map_tv_title.setText("柱上设备");
        } else {
            map_tv_title.setText("模块");

        }
        //2.1 获取附属设备一级显示
        List<ModuleType> moduleTypeList = getFushuEquipId(quebie);

        //适配器
        ArrayAdapter<ModuleType> arr_adapter21 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, moduleTypeList);
        arr_adapter21.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        map_ed_lever.setAdapter(arr_adapter21);
        map_ed_lever.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                List<ModuleType> typeClass = getTypeClass((ModuleType) map_ed_lever.getSelectedItem());
                if (typeClass.size() > 0) {
                    ArrayAdapter<ModuleType> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, typeClass);
                    //设置样式
                    arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    map_ed_head.setAdapter(arr_adapter4);
                    map_ed_head.setVisibility(View.VISIBLE);
                    map_ed_head.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            List<Module> mds = getModuleAll((ModuleType) map_ed_head.getSelectedItem(), 1).size() > 0 ? getModuleAll((ModuleType) map_ed_head.getSelectedItem(), 1) : getModuleAll((ModuleType) map_ed_head.getSelectedItem(), 2);

                            if (mds.size() > 0) {
                                map_sp_three.setVisibility(View.VISIBLE);
                                ArrayAdapter<Module> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, mds);
                                //设置样式
                                arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                                map_sp_three.setAdapter(arr_adapter4);
                                map_sp_three.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    @Override
                                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                        if (equip != null)
                                            setSpinnerItemSelectedByValue(map_sp_three, equip.getThreeName());
                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> parent) {

                                    }
                                });
                                for (Module mt : mds) {
                                    if (equip != null)
                                        if (mt.getModuleID().trim().equals((equip.getModuleID() + "").trim())) {
                                            map_sp_three.setSelection(mds.indexOf(mt));
                                            setSpinnerItemSelectedByValue(map_sp_three, equip.getThreeName());
                                            break;
                                        }
                                }
                            } else {
                                map_sp_three.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });
                    for (ModuleType mt : typeClass) {
                        if (equip != null)
                            if (mt.getModuleTypeKey().trim().equals((equip.getHead_id() + "").trim())) {
                                map_ed_head.setSelection(typeClass.indexOf(mt));
                                setSpinnerItemSelectedByValue(map_ed_head, equip.getTwoName());
                                break;
                            }
                    }

                } else {
                    List<Module> mds = getModuleAll((ModuleType) map_ed_lever.getSelectedItem(), 1).size() > 0 ? getModuleAll((ModuleType) map_ed_lever.getSelectedItem(), 1) : getModuleAll((ModuleType) map_ed_lever.getSelectedItem(), 2);

                    ArrayAdapter<Module> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, mds);
                    //设置样式
                    arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    map_sp_three.setAdapter(arr_adapter4);
                    if (equip != null) {
                        setSpinnerItemSelectedByValue(map_sp_three, equip.getThreeName());
                    }
                    for (Module mt : mds) {
                        if (equip != null) {
                            if (mt.getModuleID().trim().equals((equip.getModuleID() + "").trim())) {
                                map_sp_three.setSelection(mds.indexOf(mt));
                                break;
                            }
                        }
                    }


                    map_ed_head.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        for (ModuleType mt : moduleTypeList) {
            if (equip != null) {
                if (mt.getModuleTypeKey().trim().equals((equip.getLever_id() + "").trim())) {
                    map_ed_lever.setSelection(moduleTypeList.indexOf(mt));
                    setSpinnerItemSelectedByValue(map_ed_lever, equip.getName());
                    map_ed_four.setText(equip.getAmount() + "");
                    break;
                }
            }
        }
        if (equip != null) {
            map_ed_bh.setText(equip.getEqupmentNumber() == null ? "01" : equip.getEqupmentNumber());
        }
        //显示柱上设备模态弹窗
        AlertDialog dialogFushu = new AlertDialog.Builder(context).create();
        dialogFushu.setView(views);
        dialogFushu.show();
        //取消按钮
        map_btn_quxiao.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(views);
            dialogFushu.dismiss();
        });
        //确定按钮
        map_btn_queding.setOnClickListener(v -> {
            if (pointTitleString.equals("设备")) {
                int ganxingNumber = 0;
                int gantouNumber = 0;
                for (int i = 0; i < equipmentList.size(); i++) {
                    /*if(equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString())&&map_ed_lever.getSelectedItem().toString().contains("柱上")){
                        ToastUtils.showShort("杆头最多能有2个");
                        return;
                    }*/
                    if (equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString()) && map_ed_lever.getSelectedItem().toString().contains("杆头")) {
                        gantouNumber++;
                    }
                    if (equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString()) && map_ed_lever.getSelectedItem().toString().contains("杆型")) {
                        ganxingNumber++;
                    }
                }
                if (gantouNumber > 1) {
                    ToastUtils.showShort("杆头最多能有2个");
                    return;
                }
                if (ganxingNumber > 1) {
                    ToastUtils.showShort("杆型最多能有2个");
                    return;
                }
            }

            if (pointTitleString.equals("杆塔")) {
                int ganxingNumber = 0;
                int gantouNumber = 0;
                for (int i = 0; i < equipmentList.size(); i++) {
                    if (equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString()) && map_ed_lever.getSelectedItem().toString().contains("杆型")) {
                        ganxingNumber++;
                    }
                    if (equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString()) && map_ed_lever.getSelectedItem().toString().contains("杆头")) {
                        gantouNumber++;
                    }
                }
                if (gantouNumber > 0) {
                    ToastUtils.showShort("杆头最多能有1个");
                    return;
                }
                if (ganxingNumber > 0) {
                    ToastUtils.showShort("杆型最多能有1个");
                    return;
                }

            }


            KeyboardUtils.hideSoftInput(views);
            dialogFushu.dismiss();
            ModuleType levelMT = (ModuleType) map_ed_lever.getSelectedItem();
            if (equip == null) {//这里是新增
                Equipment myequip = new Equipment();
                //myequip.setLever_id(Integer.parseInt(levelMT.getModuleTypeID()));
                myequip.setLever_id(levelMT.getModuleTypeKey());
                myequip.setModule_code(levelMT.getModuleCode());
                myequip.setName(levelMT.getName());
                if (map_ed_bh.getText() == null) {
                    myequip.setEqupmentNumber("01");
                } else {
                    myequip.setEqupmentNumber(map_ed_bh.getText().toString());
                }
                Module threeMT = (Module) map_sp_three.getSelectedItem();
                //如果第二级显示
                if (map_ed_head.getVisibility() == View.VISIBLE) {
                    //给一级负值
                    ModuleType headLMT = (ModuleType) map_ed_head.getSelectedItem();
                    //给二级负值
                    //myequip.setHead_id(Integer.parseInt(headLMT.getModuleTypeID().trim()));
                    myequip.setHead_id(headLMT.getModuleTypeKey());
                    myequip.setTwoName(headLMT.getName());
                } else {
                    myequip.setHead_id("0");
                    myequip.setTwoName("");
                }
                //三级赋值

                if (threeMT != null && map_sp_three.getVisibility() != View.GONE) {
                    myequip.setThreeId(threeMT.getModuleID());
                    myequip.setThreeName(threeMT.getModuleName());

                    //设置模块信息
                    myequip.setModuleID(threeMT.getModuleID());
                    myequip.setModuleTxt(threeMT.getModuleName());
                    myequip.setModule_code(threeMT.getModuleCode());
                }

                myequip.setQubie(quebie);
                myequip.setAmount((map_ed_four.getText() == null || map_ed_four.getText().toString().trim().equals("")) ? 1 : Integer.parseInt(map_ed_four.getText().toString().trim()));
                myequip.setProjectId(id);
                myequip.setPointId(cid);

                //判断能选择几个杆型杆头或柱上设备
                if (Point.getName().equals("杆塔") && quebie == 0) {
                    List<Equipment> ganxing = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Name.eq("杆型")).build().list();
                    if (myequip.getName().equals("杆型")) {
                        if (ganxing.size() < 1) {
                            App.getInstances().getDaoSession().getEquipmentDao().insert(myequip);
                        } else {
                            ToastUtils.showShort("不允许添加多个杆型");
                        }
                    } else {
                        App.getInstances().getDaoSession().getEquipmentDao().insert(myequip);
                        dialogFushu.dismiss();
                    }

                } else if (Point.getSblx().equals("柱上变压器") && quebie == 0) {
                    List<Equipment> ganxing = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Name.eq("10kV柱上变台分册")).build().list();
                    List<Equipment> gx = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Name.eq("杆型")).build().list();
                    if (myequip.getName().equals("10kV柱上变台分册")) {
                        if (ganxing.size() < 1) {
                            App.getInstances().getDaoSession().getEquipmentDao().insert(myequip);
                        } else {
                            ToastUtils.showShort("只允许添加一个");
                        }
                    } else {
                        if (gx.size() > 1) {
                            ToastUtils.showShort("杆型只允许添加两个");
                        } else {
                            App.getInstances().getDaoSession().getEquipmentDao().insert(myequip);
                        }
                        dialogFushu.dismiss();
                    }

                } else {
                    App.getInstances().getDaoSession().getEquipmentDao().insert(myequip);
                }

            } else {//修改
                //equip.setLever_id(Integer.parseInt(levelMT.getModuleTypeID()));
                equip.setLever_id(levelMT.getModuleTypeKey());
                equip.setName(levelMT.getName());
                if (map_ed_bh.getText() == null) {
                    equip.setEqupmentNumber("01");
                } else {
                    equip.setEqupmentNumber(map_ed_bh.getText().toString());
                }
                //如果第二级显示
                if (map_ed_head.getVisibility() == View.VISIBLE) {
                    //给一级负值
                    ModuleType headLMT = (ModuleType) map_ed_head.getSelectedItem();
                    //给二级负值
                    //equip.setHead_id(Integer.parseInt(headLMT.getModuleTypeID().trim()));
                    equip.setHead_id(headLMT.getModuleTypeKey());
                    equip.setTwoName(headLMT.getName());
                } else {
                    equip.setHead_id("0");
                    equip.setTwoName("");
                }
                //三级赋值
                Module threeMT = (Module) map_sp_three.getSelectedItem();
                if (threeMT != null) {
                    equip.setThreeId(threeMT.getModuleID());
                    equip.setThreeName(threeMT.getModuleName());
                } else {
                    ToastUtils.showShort("所选设备配置不全");
                    return;
                    /*equip.setThreeId("0");
                    equip.setThreeName("");*/
                }
                equip.setQubie(quebie);
                equip.setAmount((map_ed_four.getText() == null || map_ed_four.getText().toString().trim().equals("")) ? 1 : Integer.parseInt(map_ed_four.getText().toString().trim()));
                equip.setPointId(id);
                equip.setPointId(cid);
                App.getInstances().getDaoSession().getEquipmentDao().update(equip);

            }
            initData();
            addLinearLayout();
        });


    }

    /**
     * 添加设备
     */
    @SuppressLint({"SetTextI18n", "CutPasteId"})
    private void addLinearLayout() {
        linearLayout = getWindow().getDecorView().findViewById(R.id.equ_ll);
        layout = getWindow().getDecorView().findViewById(R.id.equ_ll_fu);
        /**
         * 2019年10月21日修改内容。//TODO 1308
         */
        if (equipmentList.size() == 0 && zhuzhuang == 0) {
            View view = View.inflate(context, R.layout.activity_equ_equ, null);
            equ_ed_levers = view.findViewById(R.id.equ_ed_lever);
            equ_tv_names = view.findViewById(R.id.equ_tv_name);
            equ_tv_xuan = view.findViewById(R.id.equ_tv_xuan);
            TextView equ_tv_amount = view.findViewById(R.id.equ_tv_amount);
            Button equ_btn_delete = view.findViewById(R.id.equ_btn_delete);
            if (Point.getName().trim().equals("设备")) {
                equ_tv_names.setText(shebeiName);
                equ_ed_levers.setText("设置值");

            } else {
                equ_ed_levers.setText("设置值");
                equ_tv_names.setText("杆型");

            }
            equ_tv_xuan.setVisibility(View.GONE);
            equ_tv_amount.setVisibility(View.GONE);
            equ_btn_delete.setVisibility(View.GONE);
            view.setOnClickListener(v -> {
                zhuzhuang = 0;
                equipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                //添加设备
                if (Point.getName().equals("杆塔")) {
                    if (equipmentList.size() > 1) {
                        ToastUtils.showShort("杆型杆头只能各添加一个");
                    } else {
                        addFushu(null, 0);
                    }
                } else if (Point.getName().equals("设备")) {
                    if (Point.getSblx().equals("柱上变压器")) {
                        if (equipmentList.size() > 6) {
                            ToastUtils.showShort("柱上变压器模块最多添加7个");
                        } else {
                            addFushuZhuzhang(null, 0);
                        }
                    } else {
                        if (equipmentList.size() > 0) {
                            ToastUtils.showShort("模块只能添加一个");
                        } else {
                            addFushuZhuzhang(null, 0);
                        }
                    }
                }

            });
            linearLayout.addView(view);
        }
        if (equipmentList.size() > 0) {
            linearLayout.removeAllViews();
            for (int i = 0; i < equipmentList.size(); i++) {
                View view = View.inflate(context, R.layout.activity_equ_equ, null);
                equ_ed_lever = view.findViewById(R.id.equ_ed_lever);
                equ_tv_name = view.findViewById(R.id.equ_tv_name);
                equ_tv_xuan = view.findViewById(R.id.equ_tv_xuan);
                TextView equ_tv_amount = view.findViewById(R.id.equ_tv_amount);
                Button equ_btn_delete = view.findViewById(R.id.equ_btn_delete);
                if (i == 0) {
                    equ_btn_delete.setVisibility(View.GONE);
                } else {
                    equ_btn_delete.setVisibility(View.VISIBLE);

                }
                equ_tv_name.setText(equipmentList.get(i).getName());
                mganguanGan = equipmentList.get(i).getName();
                if (Point.getName().equals("设备")) {
                    equ_ed_lever.setText(equipmentList.get(i).getThreeName());

                } else {
                    equ_ed_lever.setText(equipmentList.get(i).getThreeName());

                }
                equ_tv_amount.setText(equipmentList.get(i).getAmount() == 0 ? "" : equipmentList.get(i).getAmount() + "");
                linearLayout.addView(view);
                final int finalI = i;
                equ_btn_delete.setOnClickListener(v -> {
                    final View views = View.inflate(context, R.layout.activity_map_dialog, null);
                    AlertDialog dialog = new AlertDialog.Builder(context).create();
                    dialog.setView(views);
                    dialog.show();
                    Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
                    Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
                    map_btn_queding.setOnClickListener(view12 -> {
                        dialog.dismiss();
                        if (equipmentList.size() > 1) {
                            App.getInstances().getDaoSession().getEquipmentDao().deleteByKey(equipmentList.get(finalI).getId());
                            initData();
                            addLinearLayout();
                        } else {
                            App.getInstances().getDaoSession().getEquipmentDao().deleteByKey(equipmentList.get(finalI).getId());
                            linearLayout.removeAllViews();
                        }
                    });

                    map_btn_quxiao.setOnClickListener(view1 -> dialog.dismiss());

                });
                equ_tv_xuan.setOnClickListener(v -> {
                    if (Point.getName().equals("设备")) {//设备
                        addFushuZhuzhang(equipmentList.get(finalI), 0);

                    } else {
                        addFushu(equipmentList.get(finalI), 0);
                    }

                });
            }
        }
        //添加的设备不为空时，添加新的View
        if (getEquipmentList.size() == 0 && zhuzhuang == 2 && isFirst || getEquipmentList.size() == 0 && zhuzhuang == 0 && isFirst) {
            if (!Point.getName().equals("设备") && !Point.getName().equals("地形点")) {
                View view1 = View.inflate(context, R.layout.activity_equ_equ, null);
                TextView equ_ed_lever1 = view1.findViewById(R.id.equ_ed_lever);
                TextView equ_tv_name1 = view1.findViewById(R.id.equ_tv_name);
                TextView equ_tv_xuan1 = view1.findViewById(R.id.equ_tv_xuan);
                Button delet1 = view1.findViewById(R.id.equ_btn_delete);
                equ_ed_lever1.setText("无");
                equ_tv_xuan1.setVisibility(View.GONE);
                equ_tv_name1.setVisibility(View.GONE);
                delet1.setVisibility(View.GONE);
                layout.addView(view1);

            }
        }

        //添加的附属设备设备不为空时，添加新的View
        if (getEquipmentList.size() > 0) {
            layout.removeAllViews();
            for (int i = 0; i < getEquipmentList.size(); i++) {
                View view = View.inflate(context, R.layout.activity_equ_equ, null);
                TextView equ_ed_lever = view.findViewById(R.id.equ_ed_lever);
                TextView equ_tv_name = view.findViewById(R.id.equ_tv_name);
                TextView equ_tv_xuan = view.findViewById(R.id.equ_tv_xuan);
                TextView equ_tv_amount = view.findViewById(R.id.equ_tv_amount);
                Button equ_btn_delete = view.findViewById(R.id.equ_btn_delete);

                try {
                    equ_tv_name.setText(getEquipmentList.get(i).getName());
                    equ_ed_lever.setText(getEquipmentList.get(i).getThreeName() == null ? "" : getEquipmentList.get(i).getThreeName());
                    equ_tv_amount.setText(getEquipmentList.get(i).getAmount() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                layout.addView(view);
                final int finalI = i;
                equ_btn_delete.setOnClickListener(v -> {
                    final View views = View.inflate(context, R.layout.activity_map_dialog, null);
                    AlertDialog dialog = new AlertDialog.Builder(context).create();
                    dialog.setView(views);
                    dialog.show();
                    Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
                    Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
                    map_btn_queding.setOnClickListener(view12 -> {
                        dialog.dismiss();

                        if (getEquipmentList.size() > 1) {
                            App.getInstances().getDaoSession().getEquipmentDao().deleteByKey(getEquipmentList.get(finalI).getId());
                            initData();
                            addLinearLayout();
                        } else {
                            App.getInstances().getDaoSession().getEquipmentDao().deleteByKey(getEquipmentList.get(finalI).getId());
                            layout.removeAllViews();
                            //删除之后查找是否有
                            getEquipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Qubie.eq(2)).build().list();
                            //添加的设备不为空时，添加新的View
                            if (getEquipmentList.size() == 0 || zhuzhuang == 2) {
                                if (!Point.getName().equals("设备")) {
                                    View view1 = View.inflate(context, R.layout.activity_equ_equ, null);
                                    TextView equ_ed_lever1 = view1.findViewById(R.id.equ_ed_lever);
                                    TextView equ_tv_name1 = view1.findViewById(R.id.equ_tv_name);
                                    TextView equ_tv_xuan1 = view1.findViewById(R.id.equ_tv_xuan);
                                    Button delet1 = view1.findViewById(R.id.equ_btn_delete);
                                    equ_ed_lever1.setText("无");
                                    equ_tv_xuan1.setVisibility(View.GONE);
                                    equ_tv_name1.setVisibility(View.GONE);
                                    delet1.setVisibility(View.GONE);
                                    layout.addView(view1);

                                }
                            }
                        }
                    });

                    map_btn_quxiao.setOnClickListener(view1 -> dialog.dismiss());


                });
                equ_tv_xuan.setOnClickListener(v -> {
                    addFushuZhuzhang(getEquipmentList.get(finalI), 2);
                });
            }
        }
    }

    private void initRecyclerView() {
        if (photosList.size() > 0) {
            for (int i = 0; i < photosList.size(); i++) {
                Log.e("photoPath==", photosList.get(i).getPath());
                imageBeanList.add(new ImageBean(photosList.get(i).getName(), photosList.get(i).getPath()));
            }
        }
        RecyclerView mEquRecyclerView = findViewById(R.id.equ_recyclerView);
        adapter = new ReleaseMsgAdapter(this, imageBeanList);
        mEquRecyclerView.setAdapter(adapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mEquRecyclerView.setLayoutManager(gridLayoutManager);
        adapter.setOnDeleteItemListener(this);
        //多媒体不为空时，显示RecyclerView
        mEquRecyclerView.getRecycledViewPool();
        mEquRecyclerView.getRecycledViewPool().setMaxRecycledViews(0, 10);

    }

    @Override
    public void OnDeleteItem(int position) {
        beanList.add(imageBeanList.get(position));
        imageBeanList.remove(position);
        //FileUtils.deleteFile(imageBeanList.get(position).getPath());
        adapter.notifyDataSetChanged();
    }

    /**
     * 按钮的点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_ib_back: {
                deletPointLine();
                MapActivity.isProgressShow = false;
                finish();
            }
            break;
            case R.id.activity_tv_save:
            case R.id.map_btn_cancel:
                deletPointLine();
                MapActivity.isProgressShow = false;
                finish();
                break;
            case R.id.map_btn_add:
                MapActivity.isProgressShow = true;
                save();
                break;
            //TODO 弹窗   模块选择弹窗
            case R.id.equ_btn_equ:
                zhuzhuang = 0;
                equipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                //添加设备
                if (Point.getName().equals("杆塔")) {
                    if (equipmentList.size() > 1) {
                        ToastUtils.showShort("杆型杆头只能各添加一个");
                    } else {
                        addFushu(null, 0);
                    }
                } else if (Point.getName().equals("设备")) {
                    if (Point.getSblx().equals("柱上变压器")) {
                        if (equipmentList.size() > 6) {
                            ToastUtils.showShort("柱上变压器模块最多添加7个");
                        } else {
                            addFushuZhuzhang(null, 0);
                        }
                    } else {
                        if (equipmentList.size() > 0) {
                            ToastUtils.showShort("模块只能添加一个");
                        } else {
                            addFushuZhuzhang(null, 0);
                        }
                    }
                }
                break;
            case R.id.equ_btn_add:
                //添加附属设备
                zhuzhuang = 2;
                addFushuZhuzhang(null, 2);
                break;
            case R.id.boxChangeJl:
                initBoxChangeJl();
                break;
            case R.id.gotoProgramPage:
                //电缆井问题页面
                Bundle bundle = new Bundle();
                bundle.putLong("pointId", Point.getId());
                bundle.putString("flag",Point.getEquipType_name());
                startIntent(CableWellProblemPageActivity.class, bundle);
                break;

        }
    }

    //初始化计量箱
    private void initBoxChangeJl() {
        BoxBxChangeWindow alertDialogss = new BoxBxChangeWindow(this).setContentViewId(R.layout.activity_equ_fsss_dialog).setmapParameters(5, cid, id, null);
        alertDialogss.pop();
    }

    private RecyclerView equ_fsss_rv;
    //regiona 附属设置适配器
    private RecyclerView.Adapter cementProductsAdapter;

    private void initBoxChangeList() {
        List<Equipment> cequpments = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Qubie.eq(5)).build().list();
        cementProductsAdapter = new CementProductAdapter(this, cequpments, cid, id);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(EquActivity.this);
        equ_fsss_rv.setLayoutManager(layoutManager);
        equ_fsss_rv.setAdapter(cementProductsAdapter);
        cementProductsAdapter.notifyDataSetChanged();
    }

    /**
     * 删除点和线 如果点击页面点取消以及返回按钮或者手机系统所带的系统时候
     */
    private void deletPointLine() {
        //删除点和线操作
        List<Line> lineFromptA2PtB = new ArrayList<>();
        if (flag != null && flag.equals("0") && ps != null) {
            Log.e("wfff", "222");
            List<Line> allLines = App.getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.End_id.eq(ps.getUid()), LineDao.Properties.Start_id.eq(ps.getUid())).build().list();
            lineFromptA2PtB.addAll(allLines);
            for (int i = 0; i < lineFromptA2PtB.size(); i++) {
                App.getInstances().getDaoSession().getLineDao().delete(lineFromptA2PtB.get(i));
            }
            App.getInstances().getDaoSession().getPointDao().delete(ps);
        } else {
            Log.e("wfff", "llll");
        }
    }

    @Override
    public void onBackPressed() {
        //删除点和线操作
        deletPointLine();
        MapActivity.isProgressShow = false;
        super.onBackPressed();
    }

    ArrayList<Module> gangaoArray = new ArrayList<>();

    /**
     * 添加附属设备
     */
    @SuppressLint("SetTextI18n")
    private void addFushu(Equipment equip, int quebie) {
        /**
         * 2019年10月22日修改开始
         */
        final View views = View.inflate(context, R.layout.activity_equ_dialog_wf, null);
        final View viewsWf = View.inflate(context, R.layout.activity_equ_dialog, null);
        final Spinner map_ed_lever = views.findViewById(R.id.map_ed_lever);
        final Spinner map_ed_head = views.findViewById(R.id.map_ed_head);
        final Spinner map_ed_shaojing = views.findViewById(R.id.map_ed_shaojing);
        final Spinner map_ed_ganxing = views.findViewById(R.id.map_ed_ganxing);
        final Spinner map_sp_three = views.findViewById(R.id.map_sp_three);
        final EditText map_ed_four = views.findViewById(R.id.map_ed_four);
        final LinearLayout gangao_line = views.findViewById(R.id.gangao_line);


        TextView mapTvNum = views.findViewById(R.id.mapTvNum);
        Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
        Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
        TextView map_tv_title = views.findViewById(R.id.map_tv_title);


        if (Point.getSblx().equals("电缆保护管")) {
            map_ed_four.setHint("距离（米）");
            mapTvNum.setText("设备长度");
        }

        if (quebie == 2) {
            map_tv_title.setText("柱上设备");

        } else {
            map_tv_title.setText("选型");

        }

        //类型wf
        List<ModuleType> moduleTypeList = getLiebie();
        //适配器
        ArrayAdapter<ModuleType> arr_adapter21 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, moduleTypeList);
        arr_adapter21.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        map_ed_lever.setAdapter(arr_adapter21);
        if (equip != null) {
            if (equip.getFourId() != null) {
                setSpinnerProjectelectedByValue(map_ed_head, equip.getFourId());
            }
            if (equip.getFourName() != null) {
                setSpinnerProjectelectedByValue(map_ed_shaojing, equip.getFourName());
            }

            map_ed_four.setText(equip.getAmount() + "");
            for (int i = 0; i < moduleTypeList.size(); i++) {
                if (moduleTypeList.get(i).getName().equals(equip.getName())) {
                    map_ed_lever.setSelection(i);
                    break;
                }
            }
        }

        map_ed_lever.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ModuleType typeClass = moduleTypeList.get(position);
                if (typeClass.getName().equals("钢管杆")) {
                    gangao_line.setVisibility(View.GONE);
                } else {
                    gangao_line.setVisibility(View.VISIBLE);

                }
                //获取杆高这些的类型。
                gangaoArray = getGangaoResult(typeClass.getModuleTypeKey());
                ///最终复制的内容。
                ArrayAdapter<Module> ganxinAdapter = new ArrayAdapter<Module>(EquActivity.this, android.R.layout.simple_spinner_item, gangaoArray);
                ganxinAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_ed_ganxing.setAdapter(ganxinAdapter);
                if (equip != null) {
                    for (int i = 0; i < gangaoArray.size(); i++) {
                        if (gangaoArray.get(i).getModuleName().equals(equip.getThreeName())) {
                            map_ed_ganxing.setSelection(i);
                            break;
                        }
                    }
                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //setSpinnerItemSelectedByValue(map_ed_head,map_ed_head.getSelectedItem().toString());
        map_ed_head.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<Module> gangaoNew = new ArrayList<>();
                for (Module moduleInser : gangaoArray) {
                    if ((moduleInser.getModuleName().contains(map_ed_head.getSelectedItem().toString()) || map_ed_head.getSelectedItem().toString().equals("全部"))
                            && (moduleInser.getModuleName().contains(map_ed_shaojing.getSelectedItem().toString()) || map_ed_shaojing.getSelectedItem().toString().equals("全部"))) {
                        gangaoNew.add(moduleInser);
                    }
                }
                ArrayAdapter<Module> ganxinAdapter = new ArrayAdapter<Module>(EquActivity.this, android.R.layout.simple_spinner_item, gangaoNew);
                ganxinAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_ed_ganxing.setAdapter(ganxinAdapter);
                if (equip != null) {
                    for (int i = 0; i < gangaoNew.size(); i++) {
                        if (gangaoNew.get(i).getModuleName().equals(equip.getThreeName())) {
                            map_ed_ganxing.setSelection(i);
                            break;
                        }
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        map_ed_shaojing.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<Module> gangaoNew = new ArrayList<>();
                for (Module moduleInser : gangaoArray) {
                    if ((moduleInser.getModuleName().contains(map_ed_head.getSelectedItem().toString()) || map_ed_head.getSelectedItem().toString().equals("全部"))
                            && (moduleInser.getModuleName().contains(map_ed_shaojing.getSelectedItem().toString()) || map_ed_shaojing.getSelectedItem().toString().equals("全部"))) {
                        gangaoNew.add(moduleInser);
                    }
                }

                ArrayAdapter<Module> ganxinAdapter = new ArrayAdapter<Module>(EquActivity.this, android.R.layout.simple_spinner_item, gangaoNew);
                ganxinAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_ed_ganxing.setAdapter(ganxinAdapter);
                if (equip != null) {
                    for (int i = 0; i < gangaoNew.size(); i++) {
                        if (gangaoNew.get(i).getModuleName().equals(equip.getThreeName())) {
                            map_ed_ganxing.setSelection(i);
                            break;
                        }
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //显示柱上设备模态弹窗
        AlertDialog dialogFushu = new AlertDialog.Builder(context).create();
        dialogFushu.setView(views);
        dialogFushu.show();
        //取消按钮
        map_btn_quxiao.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(views);
            dialogFushu.dismiss();
        });
        //确定按钮
        map_btn_queding.setOnClickListener(v -> {
            if (pointTitleString.equals("设备")) {
                int ganxingNumber = 0;
                int gantouNumber = 0;
                int zhushangNumber = 0;

                for (int i = 0; i < equipmentList.size(); i++) {
                    if (equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString()) && map_ed_lever.getSelectedItem().toString().contains("柱上")) {
                        zhushangNumber++;
                    }
                    if (equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString()) && map_ed_lever.getSelectedItem().toString().contains("杆头")) {
                        gantouNumber++;
                    }
                    if (equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString()) && map_ed_lever.getSelectedItem().toString().contains("杆型")) {
                        ganxingNumber++;
                    }
                }
                if (zhushangNumber > 1) {
                    ToastUtils.showShort("柱上变压只能有一个");
                    return;
                }
                if (gantouNumber > 1) {
                    ToastUtils.showShort("杆头最多能有2个");
                    return;
                }
                if (ganxingNumber > 1) {
                    ToastUtils.showShort("杆型最多能有2个");
                    return;
                }
            }

            if (pointTitleString.equals("杆塔")) {
                isFirst = false;
                int ganxingNumber = 0;
                int gantouNumber = 0;
                for (int i = 0; i < equipmentList.size(); i++) {
                    if (equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString()) && map_ed_lever.getSelectedItem().toString().contains("杆型")) {
                        ganxingNumber++;
                    }
                    if (equipmentList.get(i).getName().contains(map_ed_lever.getSelectedItem().toString()) && map_ed_lever.getSelectedItem().toString().contains("杆头")) {
                        gantouNumber++;
                    }
                }
                if (gantouNumber > 0) {
                    ToastUtils.showShort("杆头最多能有1个");
                    return;
                }
                if (ganxingNumber > 0) {
                    ToastUtils.showShort("杆型最多能有1个");
                    return;
                }

            }


            KeyboardUtils.hideSoftInput(views);
            ModuleType levelMT = (ModuleType) map_ed_lever.getSelectedItem();
            if (equip == null) {//这里是新增
                Equipment myequip = new Equipment();
                //myequip.setLever_id(Integer.parseInt(levelMT.getModuleTypeID()));
                myequip.setLever_id(levelMT.getModuleTypeKey());
                myequip.setModule_code(levelMT.getModuleCode());
                mganguanGan = levelMT.getName();
                myequip.setName(levelMT.getName());

                Module threeMT = (Module) map_sp_three.getSelectedItem();
                //如果第二级显示
                //给一级负值
                ModuleType headLMT = (ModuleType) map_ed_lever.getSelectedItem();
                myequip.setHead_id(headLMT.getModuleTypeKey());//一级

                //给2级负值
                myequip.setTwoName(headLMT.getName());

                //TODO 2xml
                Module ganxing = (Module) map_ed_ganxing.getSelectedItem();
                if (ganxing != null) {
                    myequip.setThreeId(ganxing.getModuleID());
                    myequip.setThreeName(ganxing.getModuleName());

                    //设置模块信息
                    myequip.setModuleID(ganxing.getModuleID());
                    myequip.setModuleTxt(ganxing.getModuleName());
                    myequip.setModule_code(ganxing.getModuleCode());

                    //设置杆高属性
                    for (int i = 0; i < map_ed_head.getAdapter().getCount(); i++) {
                        if (ganxing.getModuleName().contains(map_ed_head.getAdapter().getItem(i).toString())) {
                            myequip.setFourId(map_ed_head.getAdapter().getItem(i).toString());
                            break;
                        }
                    }

                    //设置稍径属性
                    for (int i = 0; i < map_ed_shaojing.getAdapter().getCount(); i++) {
                        if (ganxing.getModuleName().contains(map_ed_shaojing.getAdapter().getItem(i).toString())) {
                            myequip.setFourName(map_ed_shaojing.getAdapter().getItem(i).toString());
                            break;
                        }
                    }

                } else {
                    ToastUtils.showShort("没有对应的杆型");
                    return;
                }
                myequip.setQubie(quebie);
                myequip.setAmount((map_ed_four.getText() == null || map_ed_four.getText().toString().trim().equals("")) ? 1 : Integer.parseInt(map_ed_four.getText().toString().trim()));
                myequip.setProjectId(id);
                myequip.setPointId(cid);

                //判断能选择几个杆型杆头或柱上设备
                if (Point.getName().equals("杆塔") && quebie == 0) {
                    List<Equipment> ganxing1 = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                    if (ganxing1.size() < 1) {
                        App.getInstances().getDaoSession().getEquipmentDao().insert(myequip);
                    } else {
                        ToastUtils.showShort("不允许添加多个杆型");
                    }
                    dialogFushu.dismiss();
                } else if (Point.getSblx().equals("柱上变压器") && quebie == 0) {
                    List<Equipment> ganxing1 = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Name.eq("10kV柱上变台分册")).build().list();
                    List<Equipment> gx = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(cid), EquipmentDao.Properties.Name.eq("杆型")).build().list();

                    if (myequip.getName().equals("10kV柱上变台分册")) {
                        if (ganxing1.size() < 1) {
                            App.getInstances().getDaoSession().getEquipmentDao().insert(myequip);
                        } else {
                            ToastUtils.showShort("只允许添加一个");
                        }
                    } else {
                        if (gx.size() > 1) {
                            ToastUtils.showShort("杆型只允许添加两个");
                        } else {
                            App.getInstances().getDaoSession().getEquipmentDao().insert(myequip);
                        }
                        dialogFushu.dismiss();
                    }
                } else {
                    App.getInstances().getDaoSession().getEquipmentDao().insert(myequip);
                }

            } else {//修改
                //equip.setLever_id(Integer.parseInt(levelMT.getModuleTypeID()));
                equip.setLever_id(levelMT.getModuleTypeKey());
                equip.setName(levelMT.getName());
                mganguanGan = levelMT.getName();
                //如果第二级显示
                ModuleType headLMT = (ModuleType) map_ed_lever.getSelectedItem();
                equip.setHead_id(headLMT.getModuleTypeKey());//一级
                //给2级负值
                equip.setTwoName(headLMT.getName());

                //TODO 2 xml
                /**serializer.attribute(null, "Amount", equipment.getAmount() + "");
                 serializer.attribute(null, "Module_ID", equipment.getThree_id() + "");
                 serializer.attribute(null, "Module_Name", equipment.getThreeName() + "");
                 serializer.attribute(null, "ModuleXH_ID", equipment.getThree_id() + "");
                 serializer.attribute(null, "ModuleXH_Name", equipment.getThreeName() + "");
                 serializer.attribute(null, "ModuleZL_ID", equipment.getHead_id() + "");
                 serializer.attribute(null, "ModuleZL_Name", equipment.getTwo_name() + "");
                 serializer.attribute(null, "ModuleFL_ID", equipment.getLever_id() + "");
                 serializer.attribute(null, "ModuleFL_Name", equipment.getName() + "");
                 serializer.attribute(null, "Module_Code", getModleCode(equipment.getThree_id() + "") + "");
                 serializer.attribute(null, "PID", equipment.getId() + "");
                 **/
                Module ganxing = (Module) map_ed_ganxing.getSelectedItem();
                if (ganxing != null) {
                    //TODO ModuleXH_ID getThree_id
                    equip.setThreeId(ganxing.getModuleID());
                    //TODO ModuleXH_Name getThreeName
                    equip.setThreeName(ganxing.getModuleName());
                    //设置模块信息
                    equip.setModuleID(ganxing.getModuleID());
                    equip.setModuleTxt(ganxing.getModuleName());
                    equip.setModule_code(ganxing.getModuleCode());

                    //设置杆高属性
                    for (int i = 0; i < map_ed_head.getAdapter().getCount(); i++) {
                        if (ganxing.getModuleName().contains(map_ed_head.getAdapter().getItem(i).toString())) {
                            equip.setFourId(map_ed_head.getAdapter().getItem(i).toString());
                            break;
                        }
                    }

                    //设置稍径属性
                    for (int i = 0; i < map_ed_shaojing.getAdapter().getCount(); i++) {
                        if (ganxing.getModuleName().contains(map_ed_shaojing.getAdapter().getItem(i).toString())) {
                            equip.setFourName(map_ed_shaojing.getAdapter().getItem(i).toString());
                            break;
                        }
                    }
                } else {
                    ToastUtils.showShort("没有对应的杆型");
                    return;
                }


                //三级赋值
                equip.setQubie(quebie);
                equip.setAmount((map_ed_four.getText() == null || map_ed_four.getText().toString().trim().equals("")) ? 1 : Integer.parseInt(map_ed_four.getText().toString().trim()));
                //equip.setItemID(id);
                //equip.setPointId(cid);


                List<Equipment> equipmentSSSS1 = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.ProjectId.eq(id)).build().list();

                App.getInstances().getDaoSession().getEquipmentDao().update(equip);

            }
            List<Equipment> equipmentSSSS = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.ProjectId.eq(id)).build().list();
            dialogFushu.dismiss();
            initData();
            addLinearLayout();
        });


    }

    /**
     * 过滤选型选项
     */
    private void filterOptions() {

    }

    /**
     * 获取杆高这些信息
     *
     * @param moduleTypeKey
     */
    private ArrayList<Module> getGangaoResult(String moduleTypeKey) {
        ArrayList<Module> module_array = new ArrayList<>();
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from Module m where m.ModuleTypeKey =" + "'" + moduleTypeKey + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            Module module = new Module();
            module.setModuleID(cursor.getString(0));
            module.setModuleName(cursor.getString(1));
            module.setModuleTypeKey(cursor.getString(2));
            module.setModuleCode(cursor.getString(3));
            module_array.add(module);
        }

        cursor.close();


        return module_array;
    }


    /**
     * 获取moudle表数据
     *
     * @param mt   /
     * @param flag 1为-的数据 2为正常数据
     * @return /
     */
    private List<Module> getModuleAll(ModuleType mt, int flag) {
        mtAllSet.clear();
        Set<ModuleType> mtAll = getAllSubModuleType(mt);

        List<Module> mAll = new ArrayList<>();
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        for (ModuleType m : mtAll) {
            Cursor cursor;
            if (flag == 1) {
                cursor = db.rawQuery("select m.* from module m where m.moduletypekey = " + "'" + m.getModuleTypeKey() + "'  and cast(m.ModuleID as int) > 9999 and  cast(m.ModuleID as int) < 12000", null);//此处的db是表名，name是列名
            } else {
                cursor = db.rawQuery("select m.* from module m where m.moduletypekey = " + "'" + m.getModuleTypeKey() + "'", null);//此处的db是表名，name是列名
            }
            while (cursor.moveToNext()) {
                Module mod = new Module();
                mod.setModuleID(cursor.getString(0));
                mod.setModuleName(cursor.getString(1));
                mod.setModuleTypeKey(cursor.getString(2));
                mod.setModuleCode(cursor.getString(3));

                mAll.add(mod);
            }
            cursor.close();
        }

        return mAll;
    }


    private Set<ModuleType> getAllSubModuleType(ModuleType mt) {
        mtAllSet.add(mt);
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select mt.* from moduletype mt where mt.ParentKey = " + "'" + mt.getModuleTypeKey() + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModuleType moduleType = new ModuleType();
            moduleType.setModuleTypeID(cursor.getString(0));
            moduleType.setName(cursor.getString(1));
            moduleType.setModuleTypeKey(cursor.getString(2));
            moduleType.setParentKey(cursor.getString(3));

            getAllSubModuleType(moduleType);
        }
        cursor.close();


        return mtAllSet;
    }

    private List<ModuleType> getTypeClass(ModuleType selMt) {
        List<ModuleType> mtLst = new ArrayList<>();
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select mt.* from ModuleType mt where mt.ParentKey = " + "'" + selMt.getModuleTypeKey() + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModuleType moduleType = new ModuleType();
            moduleType.setModuleTypeID(cursor.getString(0));
            moduleType.setName(cursor.getString(1));
            moduleType.setModuleTypeKey(cursor.getString(2));
            moduleType.setParentKey(cursor.getString(3));
            //moduleType.setState(cursor.getString(4));
            mtLst.add(moduleType);
        }
        cursor.close();


        return mtLst;
    }


    /**
     * 添加附属设备点点id查询equip_modleType里面的
     *
     * @return 子类集合
     */
    private List<ModuleType> getFushuEquipId(int qubie) {
        List<ModuleType> moduleTypeData = new ArrayList<>();
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor;
        if (qubie == 2) {
            //select mt.* from "equip_moduleType_ Attached" ematt left join moduletype mt on mt.ModuleTypeID = ematt.ModuletypeID ORDER BY mt.id
            cursor = db.rawQuery("select mt.* from \"equip_moduleType_ Attached\" ematt left join moduletype mt on mt.ModuleTypeID = ematt.ModuletypeID  ORDER BY ematt.id", null);//此处的db是表名，name是列名
        } else {
            cursor = db.rawQuery("select mt.* from moduletype mt left join equip_moduleType ematt on mt.ModuleTypeID = ematt.ModuletypeID where ematt.equipID = " + equId + " ORDER BY ematt.id", null);//此处的db是表名，name是列名
        }
        while (cursor.moveToNext()) {
            ModuleType moduleType = new ModuleType();
            moduleType.setModuleTypeID(cursor.getString(0));
            moduleType.setName(cursor.getString(1));
            moduleType.setModuleTypeKey(cursor.getString(2));
            moduleType.setParentKey(cursor.getString(3));
            //moduleType.setState(cursor.getString(4));
            //这里去掉了故障指示器(361)改成了(3611)
            if (moduleType.getName() != null) {
                moduleTypeData.add(moduleType);
            }
        }
        cursor.close();

        return moduleTypeData;
    }


    /**
     * 保存方法
     */
    //TODO 修改方法
    private void save() {
        if (mRoadName.getText() != null&&!mRoadName.getText().toString().isEmpty()) {
            Point.setRoadName(mRoadName.getText().toString());
        }else{
            ToastUtils.showLong("请输入道路名称");
            return;
        }
        if ("电缆井".equals(Point.getEquipType_name())){
            if (map_ed_dljcc.getText()!=null&&!map_ed_dljcc.getText().toString().isEmpty()){
                Point.setDljCC(map_ed_dljcc.getText().toString());
            }else{
                ToastUtils.showLong("电缆井尺寸(米）");
                return;
            }
        }
        if (equWellSpinner.getSelectedItem() != null) {
            String wellSele = (String) equWellSpinner.getSelectedItem();
            Point.setCabwellPy(wellSele);
        }
        if (RoadLocation.getText() != null&&!RoadLocation.getText().toString().isEmpty()) {
            Point.setRoadAdress(RoadLocation.getText().toString());
        }else{
            ToastUtils.showLong("请输入道路位置");
            return;
        }
        if (srcStateSpiner.getSelectedItem() != null) {
            String srState = (String) srcStateSpiner.getSelectedItem();
            Point.setRsState(srState);
        }

        if (ghYearEt.getText() != null) {
            Point.setGhYear(ghYearEt.getText().toString());
        }
        if ("电缆井".equals(Point.getEquipType_name())){
            if (equAdressEt.getText() != null&&!equAdressEt.getText().toString().isEmpty()) {
                Point.setAddress(equAdressEt.getText().toString());
            }else{
                ToastUtils.showLong("请输入地址");
                return;
            }
        }
        if (ghYearEt.getText() != null) {
            Point.setGhYear(ghYearEt.getText().toString());
        }
        if ((srcSpeEt.getText() != null&&!srcSpeEt.getText().toString().isEmpty())||Point.getEquipType_name().equals("电缆井")) {
            Point.setReSpecfs(srcSpeEt.getText().toString());
        }else{
            ToastUtils.showLong("请输入资源规格");
            return;
        }
        if (RoadNatureEt.getText() != null&&!RoadNatureEt.getText().toString().isEmpty()||Point.getEquipType_name().equals("电缆井")) {
            Point.setRoadNature(RoadNatureEt.getText().toString());
        }else{
            ToastUtils.showLong("请输入道路性质");
            return;
        }
        if(gridNameEt.getText()!=null&&!gridNameEt.getText().toString().isEmpty()){
            Point.setGridName(gridNameEt.getText().toString());

        }else{
            ToastUtils.showLong("请输入网格名称");
            return;
        }
        if (intentLine != null && intentLine.getIsT() != null && !intentLine.getIsT().isEmpty() && intentLine.getName() != null) {
            if (!tLineId.isEmpty()) {
                ToastUtils.showLong("分支线路名称:" + intentLine.getName());
                intentLine.setFenZhiLineId(tLineId);
                App.getInstances().getDaoSession().getLineDao().update(intentLine);
            }
        }

        Point.setState(map_sp_state.getSelectedItem().toString().trim());
        Point.setEquipType_name(map_sp_type.getSelectedItem().toString().trim());
        if ("".equals(map_ed_high.getText().toString().trim())) {
            Point.setHigh(map_ed_high.getText().toString().trim() + "");
        } else {
            Point.setHigh(map_ed_high.getText().toString().trim());
        }
        Equip PointEquip = (Equip) map_sp_type.getSelectedItem();
        Point.setDefaultLineType(PointEquip.getDefaultLineType());
        Point.setEquipType_id(PointEquip.getId());
        Point.setSblx(PointEquip.getName());
        Point.setIcon(PointEquip.getIcon());
        /*
        *   map_tv_locations.setText(sfm[0]);
            map_tv_locationf.setText(sfm[1]);
            map_tv_locationm.setText(sfm[2]);
            map_tv_locationss.setText(sfmm[0]);
            map_tv_locationfs.setText(sfmm[1]);
            map_tv_locationms.setText(sfmm[2]);
        *  .replace("°", ";")
                .replace("′", ";")
                .replace("'", ";")
        * */
        try {
            String jinduS = map_tv_locations.getText().toString();
            String weiduS = map_tv_locationss.getText().toString();
            if (!jinduS.isEmpty() && !weiduS.isEmpty()) {
                ///根据时分秒获取仅为度
                Point.setLongitude(parseDouble(jinduS));
                Point.setLatitude(parseDouble(weiduS));
                //对应线是不是修改。
                List<Line> relateLines = getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(Point.getUid()), LineDao.Properties.End_id.eq(Point.getUid())).build().list();
                for (Line l : relateLines) {
                    if (l.getStart_id().equals(Point.getUid())) {
                        l.setLatA(Point.getLatitude() + "");
                        l.setLonA(Point.getLongitude() + "");
                        BigDecimal bg = BigDecimal.valueOf(Distance(parseDouble(l.getLatB()), parseDouble(l.getLonB()), parseDouble(l.getLatA()), parseDouble(l.getLonA()))).setScale(0, RoundingMode.UP);
                        l.setLength(bg.intValue() + "");
                        getInstances().getDaoSession().getLineDao().update(l);
                    } else if (l.getEnd_id().equals(Point.getUid())) {
                        l.setLatB(Point.getLatitude() + "");
                        l.setLonB(Point.getLongitude() + "");
                        BigDecimal bg = BigDecimal.valueOf(Distance(parseDouble(l.getLatB()), parseDouble(l.getLonB()), parseDouble(l.getLatA()), parseDouble(l.getLonA()))).setScale(0, RoundingMode.UP);
                        l.setLength(bg.intValue() + "");
                        getInstances().getDaoSession().getLineDao().update(l);
                    }
                }
            } else {
                ToastUtils.showLong("请输入正确的经纬度");
                return;
            }
        } catch (Exception e) {
            ToastUtils.showLong("输入经纬度有误");
            return;
        }
        if (viewLine.getVisibility() == View.VISIBLE) {
            Point.setEqupmentHeight(heighEtValue);
            Point.setDipOfhorizon(heighChaEtValue);

        }
        if (progress_Et.getText() != null && progress_Et.getText().toString().length() > 0 && !progress_Et.getText().toString().startsWith(".") && !progress_Et.getText().toString().startsWith("+")) {
            Point.setLineDirection(progress_Et.getText().toString());
        }
        if (!isSzFenzhigan.isChecked() && !isFenzhigan.isChecked()) {
            //如果修改成了两个都不选。那么恢复线 的 isT=0
            List<Line> isTline = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(Point.getUid())).whereOr(LineDao.Properties.ParallelPole.eq("1"), LineDao.Properties.ParallelPole.eq("2")).list();
            if (isTline.size() > 0) {//如果有两条都是十字街线这次为杆塔。需要让用户去删除这个字子节线路再操作修改。
                ToastUtils.showShort("请删除该杆塔关联的T线路或者十字接线路,再进行修改");
                return;
            }
            Point.setIsT("0");
        } else {
            //如果修改成了两个都不选。那么恢复线 的 isT=0
            List<Line> isTline = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(Point.getUid())).whereOr(LineDao.Properties.ParallelPole.eq("1"), LineDao.Properties.ParallelPole.eq("2")).list();
            List<Line> isSzline = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(Point.getUid()), LineDao.Properties.ParallelPole.eq("2")).list();
            if (isSzline.size() > 1 && isFenzhiBoolea.equals("1")) {//如果有两条都是十字街线且这次是选择的T分阶 那么修改其中一条为isT=1其他的为0
                ToastUtils.showShort("请删除其中一根十字接线路,再进行修改");
                return;

            } else {//有一个线是T或者有一个线是十字街。这里我们进行修改为我们默认的选中的isT=isFenzhiBoolea
                for (int i = 0; i < isTline.size(); i++) {
                    isTline.get(i).setParallelPole(isFenzhiBoolea);
                    App.getInstances().getDaoSession().getLineDao().update(isTline.get(i));
                }
            }

            Point.setIsT(isFenzhiBoolea);

        }
        if (map_sp_type.getSelectedItem().toString().equals("柱上变压器")) {
            if (!zhuGanSpinner.getSelectedItem().toString().equals("请选择")) {
                Point zhuGanPoint = (Point) zhuGanSpinner.getSelectedItem();
                Point.setLonA(zhuGanPoint.getUid());
                Point.setLatitude(zhuGanPoint.getLatitude() - 0.00005);
                Point.setLongitude(zhuGanPoint.getLongitude() - 0.000032);
            } else {
                ToastUtils.showShort("请选择主杆");
                return;
            }
            if (!fuGanSpinner.getSelectedItem().toString().equals("请选择")) {
                Point fuGanPoint = (Point) fuGanSpinner.getSelectedItem();
                Point.setLonB(fuGanPoint.getUid());
            } else {
                Point.setLonB("");
            }
            List<Line> guanlianXianZhushang = App.getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(Point.getUid()), LineDao.Properties.End_id.eq(Point.getUid())).build().list();
            //删除对应的设备、模块、柱上设备等
            for (Line line : guanlianXianZhushang) {
                App.getInstances().getDaoSession().getLineDao().delete(line);
            }
        }
        if (intentLine != null && map_sp_type.getSelectedItem().toString().equals("柱上变压器")) {//跟新线
            intentLine.setType("架空线路");
            intentLine.setTypeId("11");
            App.getInstances().getDaoSession().getLineDao().update(intentLine);
        }
        /**
         * 2019年10月16日王飞修改
         * 自动保存相关信息，要有记忆功能
         * 1:这里第一步进行数据库查找没有裤就创建。
         * List<AlertPointNameTable>alertPointNameTables=App.getInstances().getDaoSession().getAlertPointNameTableDao().queryBuilder().build().list();
         *         if(alertPointNameTables.isEmpty()){//插入表
         *             AlertPointNameTable alertPointNameTable=new AlertPointNameTable();
         *             alertPointNameTable.setSblx("");
         *             alertPointNameTable.setMark("");
         *             App.getInstances().getDaoSession().getAlertPointNameTableDao().insert(alertPointNameTable);
         *         }else{//判断和修改
         *
         *}
         *
         * */

        Point.setMark(map_ed_name.getText().toString().trim());
        Point.setNote(map_ed_note.getText().toString().trim());
        //TODO 如果是钢管杆那么我们进行legendTypkey。如果是其他的就用默认的哦。
        if (!mganguanGan.isEmpty() && mganguanGan.equals("钢管杆")) {
            Point.setLegendTypeKey("TY_GGG");

        } else {
            if (PointEquip.getName().equals("变电站")) {
                Point.setLegendTypeKey("TY_35kVBDZ");
            } else {
                Point.setLegendTypeKey(getLineRemarker(PointEquip.getName()));

            }
        }
        //Point.setLegendTypeKey(getLineRemarker(map_sp_type.getSelectedItem().toString()));
        if (Point.getName().equals("地形点")) {
            Point.setCategory(map_sp_dixing_sort.getSelectedItem().toString().trim());
            Point.setGlsb("");
            Point.setState(map_sp_state.getSelectedItem().toString().trim());
            Point.setEquipType_name(map_sp_type.getSelectedItem().toString().trim());
            Point.setWidth(map_ed_length.getText().toString());
            Point.setLength(map_ed_width.getText().toString());
            if (!(Point.getEquipType_name().equals("电缆拐点") || Point.getEquipType_name().equals("连接点") || Point.getEquipType_name().equals("下户拐点"))) {
                List<Line> relateLines = App.getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(Point.getUid()), LineDao.Properties.End_id.eq(Point.getUid())).build().list();
                //删除对应的设备、模块、柱上设备等
                if (equipmentList.size() > 0) {
                    for (Equipment equipment : equipmentList) {
                        App.getInstances().getDaoSession().getEquipmentDao().delete(equipment);
                    }
                }
                //删除线关联点。
                if (relateLines.size() > 0) {
                    for (Line line : relateLines) {
                        //TODO 删除所有点关联点线
                        App.getInstances().getDaoSession().getLineDao().delete(line);
                    }
                }
            }


        }


        if (map_sp_equ.getSelectedItem() != null) {
            Point.setGlsb(map_sp_equ.getSelectedItem().toString());
        } else {
            Point.setGlsb("");
        }

      /*  if(map_sp_type.getSelectedItem().toString().equals("柱上变压器")){
            Point.setCategory(map_sp_dixing_sort.getSelectedItem().toString().trim());
            Point.setGlsb("");
        }*/


        /**
         * 这里设置点点链接。
         * 1.获取关联点
         * 2.
         */
        /*//1. 获取关联点
        Log.e("关联点=",map_sp_equ.getSelectedItem().toString());
        Point PointGlsb = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Glsb.eq(map_sp_equ.getSelectedItem().toString())).build().list().get(0);
        //2. */


        //Point.setGlsb(map_sp_equ.getSelectedItem().toString().trim());
        // Point PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Mark.eq(map_sp_equ.getSelectedItem().toString().trim())).build().list().get(0);
          /*List<Line> lines = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(Point.getUid())).build().list();
            if (lines.size() > 0) {
                Line line = lines.get(0);
                line.setLatB(PointList.getLat());
                line.setLonB(PointList.getLon());
                line.setStart_id(Point.getUid());
                line.setEnd_id(PointList.getUid());
                if (PointList.getName().equals("杆塔") && Point.getName().equals("杆塔")) {
                    line.setType("架空线路");
                    line.setType_Id("11");
                } else {
                    line.setType("电缆");
                    line.setType_Id("42");
                }

                assert line != null;
                List<Point> PointLists = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(id)).build().list();
                if (PointLists.size() > 1 && PointList.getGlsb() != null && !PointList.getGlsb().equals("")) {
                    if (PointList.getId() != 1) {
                        BigDecimal bg = new BigDecimal(Distance(Double.valueOf(line.getLatA()), Double.valueOf(line.getLonA()), Double.valueOf(PointList.getLat()), Double.valueOf(PointList.getLon()))).setScale(2, RoundingMode.UP);
                        double lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        line.setLength(lengths + "");
                        App.getInstances().getDaoSession().getLineDao().update(line);
                    }
                }
            }*/
        Point.setId(cid);
        Log.e(TAG, "save: " + Point.toString1());
        App.getInstances().getDaoSession().getPointDao().update(Point);

        //删除图片操作
        if (beanList.size() > 0) {
            for (int i = 0; i < beanList.size(); i++) {
                for (int j = 0; j < photosList.size(); j++) {
                    if (photosList.get(j).getPath().equals(beanList.get(i).getPath())) {
                        App.getInstances().getDaoSession().getPhotosDao().delete(photosList.get(j));
                        FileUtils.deleteFile(beanList.get(i).getPath());
                    }
                }
            }
        }


        if (intentLine != null && selectedType != 0) {//表示不是第一次和修改。
            //TODO 去跟新所有插入点
            xuanxinLine.clear();
            //块
            //第0次才有所以intentLine
            List<Line> oneLines = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(intentLine.getStart_id()), LineDao.Properties.End_id.eq(intentLine.getEnd_id())).list();
            List<Line> twoLines = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(intentLine.getEnd_id()), LineDao.Properties.End_id.eq(intentLine.getStart_id())).list();
            xuanxinLine.addAll(oneLines);
            xuanxinLine.addAll(twoLines);

            //TODO 第一步获取StatPoint 和endPoint
            Point_a = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(intentLine.getStart_id())).build().list().get(0);
            Point_b = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(intentLine.getEnd_id())).build().list().get(0);
            latLng_a = new LatLng(Point_a.getLatitude(), Point_a.getLongitude());
            latLng_b = new LatLng(Point_b.getLatitude(), Point_b.getLongitude());
            //TODO 第2步获取StatPoint 和endPoint
            List<LatLng> allLatLng = getLatLng();
            Log.e("allLatLng", allLatLng.toString());
            if (allLatLng.size() > 0) {
                //TODO 第三部 插入点Line<Point>
                addPointAll(allLatLng);
            }

        }
        if (imageBeanList.size() > 0) {
            savePhoto();
        }
        //App.getInstances().getDaoSession().getLineDao().delete(intentLine);
        //ToastUtils.showShort("保存成功");
        MapActivity.isProgressShow = true;
        finish();
    }

    /**
     * 保存图片
     */
    private void savePhoto() {
        for (int i = 0; i < imageBeanList.size(); i++) {
            if (!imageBeanList.get(i).getPath().contains("/storage/emulated/0/bhne/")) {
                //Bitmap bitmap = BitmapFactory.decodeFile(imageBeanList.get(i).getPath());
                String mImageName = ps.getMark() + "_" + Calendar.getInstance().getTimeInMillis() + ".jpg";
                //创建图片文件
                File mImageFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/" + getPath() +File.separator+map_ed_name.getText().toString(), mImageName);
                mImageFile.getParentFile().mkdirs();
                FileUtils.copyFile(imageBeanList.get(i).getPath(), mImageFile.getPath());
                //savePhotoToSD(bitmap, mImageFile);
                Photos photos = new Photos();
                photos.setId(null);
                photos.setName(mImageName);
                photos.setPath(mImageFile.getPath());
                photos.setPoints_id(cid);
                App.getInstances().getDaoSession().getPhotosDao().insert(photos);
            }
        }
    }

    /**
     * 得到当前Project名称
     */
    private String getPath() {
        Project project = null;
        if (id != 0) {
            List<Project> ProjectList = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().list();
            project = ProjectList.get(0);
        }

        assert project != null;
        return project.getName();
    }

    /**
     * @param str 查询的序号
     * @return Equip
     */
    public List<Equip> getEquIp(int str) {
        List<Equip> strings = null;
        try {
            strings = new ArrayList<>();
            SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
            assert db != null;
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType where component=" + str, null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                Equip equip = new Equip();
                equip.setId(cursor.getInt(0));
                equip.setName(cursor.getString(1));
                equip.setComponent(cursor.getString(2));
                equip.setCode(cursor.getString(3));
                equip.setDefaultLineType(cursor.getString(4));
                equip.setIcon(cursor.getString(5));
                equip.setRemark(cursor.getString(6));
                strings.add(equip);
            }
            cursor.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return strings;
    }

    /**
     * @param
     * @return Equip
     */
    public List<ModuleType> getLiebie() {
        List<ModuleType> strings = null;
        try {
            strings = new ArrayList<>();
            SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
            assert db != null;
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType mt where mt.ParentKey = '50000GT' and mt.State = '100'", null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                ModuleType equip = new ModuleType();
                equip.setName(cursor.getString(1));
                equip.setModuleTypeKey(cursor.getString(2));
                strings.add(equip);
                Log.e("index", cursor.getString(1));
            }
            cursor.close();
            @SuppressLint("Recycle") Cursor cursor1 = db.rawQuery("select * from ModuleType mt where mt.ParentKey = 'TBT_TT' and mt.State = '1'", null);//此处的db是表名，name是列名
            while (cursor1.moveToNext()) {
                ModuleType equip = new ModuleType();
                equip.setName(cursor1.getString(1));
                equip.setModuleTypeKey(cursor1.getString(2));
                strings.add(equip);
                Log.e("index", cursor.getString(1));
            }
            cursor1.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strings;
    }

    /**
     * 处理返回结果。
     *
     * @param requestCode 请求码
     * @param resultCode  结果码 成功 -1 失败 0
     * @param data        返回的数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> paths = PictureSelector.obtainMultipleResult(data);
                if (paths != null && paths.size() > 0) {
                    for (int i = 0; i < paths.size(); i++) {
                        if (paths.get(i).getCompressPath() != null) {
                            imageBeanList.add(new ImageBean(paths.get(i).getCutPath(), paths.get(i).getCompressPath()));
                        } else {
                            imageBeanList.add(new ImageBean(paths.get(i).getCutPath(), paths.get(i).getPath()));
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    /**
     * @param lever 这个用来获取设备id的
     */
    private List<Module> getModuleList(int lever) {
        List<EquipModuleType> strings = new ArrayList<>();
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from equip_moduleType where equipID=" + "'" + lever + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            EquipModuleType equip = new EquipModuleType();
            equip.setId(cursor.getInt(0));
            equip.setEquipID(cursor.getInt(1));
            equip.setModuleTypeID(cursor.getInt(2));
            strings.add(equip);
        }
        cursor.close();
        List<ModuleType> mtlst = new ArrayList<>();
        for (EquipModuleType et : strings) {
            @SuppressLint("Recycle") Cursor cursorm = db.rawQuery("select * from ModuleType where moduletypeID=" + "'" + et.getModuleTypeID() + "'", null);//此处的db是表名，name是列名
            while (cursorm.moveToNext()) {
                ModuleType mt = new ModuleType();
                mt.setModuleTypeID(cursorm.getString(0));
                mt.setName(cursorm.getString(1));
                mt.setModuleTypeKey(cursorm.getString(2));
                mt.setParentKey(cursorm.getString(3));
                mtlst.add(mt);
            }
            cursorm.close();
        }

        List<ModuleType> mtall = new ArrayList<>(mtlst);
        for (ModuleType mt : mtlst) {
            allMT.clear();
            mtall.addAll(getSubModuleTypeList(mt.getModuleTypeKey()));
        }

        List<Module> mAll = new ArrayList<>();
        for (ModuleType mt : mtall) {
            @SuppressLint("Recycle") Cursor cursorm = db.rawQuery("select * from Module where moduletypekey=" + "'" + mt.getModuleTypeKey() + "'", null);//此处的db是表名，name是列名
            while (cursorm.moveToNext()) {
                Module m = new Module();
                m.setModuleID(cursorm.getString(0));
                m.setModuleName(cursorm.getString(1));
                m.setModuleTypeKey(cursorm.getString(2));
                m.setModuleCode(cursorm.getString(3));
                m.setRemark(cursorm.getString(6));
                mAll.add(m);
            }
            cursorm.close();
        }

        return mAll;
    }

    public List<Equip> getGuPiaoDai(int str) {
        List<Equip> strings = new ArrayList<>();
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle")
        Cursor cursor = db.rawQuery("select * from EquipType where component=" + str + " order by ID", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            Equip equip = new Equip();
            equip.setId(cursor.getInt(0));
            equip.setName(cursor.getString(1));
            equip.setCode(cursor.getString(4));
            strings.add(equip);
        }
        cursor.close();

        return strings;
    }

    private List<ModuleType> getSubModuleTypeList(String parentKey) {
        List<ModuleType> mtlst = new ArrayList<>();
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursorm = db.rawQuery("select * from ModuleType where ParentKey=" + "'" + parentKey + "'", null);//此处的db是表名，name是列名
        while (cursorm.moveToNext()) {
            ModuleType mt = new ModuleType();
            mt.setModuleTypeID(cursorm.getString(0));
            mt.setName(cursorm.getString(1));
            mt.setModuleTypeKey(cursorm.getString(2));
            mt.setParentKey(cursorm.getString(3));
            mtlst.add(mt);
        }
        allMT.addAll(mtlst);
        cursorm.close();


        for (ModuleType mt : mtlst) {
            getSubModuleTypeList(mt.getModuleTypeKey());
        }
        return allMT;
    }

    ///查询线的remark
    private String getLineRemarker(String reMarkerName) {
        String ReMark = "";
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType  where name='" + reMarkerName + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ReMark = cursor.getString(6);
        }
        cursor.close();

        return ReMark;
    }

    /**
     * 查找与本条线路关联的线段
     *
     * @param
     * @param isAll (true查询所有线段,false只查询与拐点关联线段)
     * @return 返回所有线段
     */
    private Set<Line> getRelationLine(Line liness, boolean isAll) {
        Set<Line> lineSet = new HashSet<>();
        return getRelationLine(liness, isAll, lineSet);
    }

    /**
     * 查找与本条线路关联的线段
     *
     * @param line    xian
     * @param isAll   (true查询所有线段,false只查询与“拐点”关联线段)
     * @param lineSet (可用于存放结果的容器,中介者)
     * @return 返回所有线段
     */
    private Set<Line> getRelationLine(Line line, boolean isAll, Set<Line> lineSet) {
        List<Point> pointlst = App.getInstances().getDaoSession().getPointDao().queryBuilder().whereOr(PointDao.Properties.Uid.eq(line.getStart_id()), PointDao.Properties.Uid.eq(line.getEnd_id())).build().list();
        for (Point p : pointlst) {
            if (p.getName().contains("拐点") || isAll) {
                List<Line> lines = App.getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(p.getUid()), LineDao.Properties.End_id.eq(p.getUid())).build().list();
                for (int index = 0; index < lines.size(); index++) {
                    if (!lineSet.contains(lines.get(index))) {
                        if (lines.get(index).getMethodName() == null) {
                            lineSet.add(lines.get(index));
                            getRelationLine(lines.get(index), isAll, lineSet);
                        }
                    }
                }
            }
        }

        return lineSet;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }

    /**
     * 获取UUID
     *
     * @return uuid
     */
    private String getUUID() {
        return UUID.randomUUID() + "";
    }

}